在 android 个相机上添加数据
Add data on android camera
我正在尝试制作一个 android 应用程序,它可以打开相机、启动计时器并在相机上显示计时器(当前时间,每秒刷新一次)。
我设法制作了一个计时器,我设法启动了相机,但我无法弄清楚如何以及在何处添加计时器数据。
我通过单击按钮启动相机,代码如下所示:
public void onClick(View v) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, IMAGE_CAPTURE);
}
我的计时器 class 此刻在 TextView 上打印数据,如下所示:
runOnUiThread(new Runnable(){
@Override
public void run() {
textCounter.setText(strDate);
}});
如有任何帮助,我们将不胜感激!
this github link 上有一个自定义相机 class 的示例。
我会尝试在下面解释您需要做什么。
对于您的布局,您可以使用此代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="@+id/cameraPreview"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" >
<TextView
android:id="@+id/timerTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:gravity="center"
android:layout_gravity="center" /> </FrameLayout> </LinearLayout>
将以下权限添加到您的清单中:
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
创建相机 activity 并预览 class:
public class CameraActivity extends Activity implements Camera.PictureCallback,
SurfaceHolder.Callback {
private Camera camera;
private SurfaceView cameraPreview;
private FrameLayout frameLayoutCameraPreview;
private int currentCameraID = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_camera);
cameraPreview = new SurfaceView(this);
cameraPreview.setKeepScreenOn(true);
initFormElements();
/* get the current camera id */
currentCameraID = Camera.CameraInfo.CAMERA_FACING_BACK;
/* show the camera */
showCamera();
}
@SuppressWarnings("deprecation")
private void initFormElements() {
frameLayoutCameraPreview = (FrameLayout) findViewById(R.id.cameraPreview);
// initialize your textview here as well
/* configure surface holder */
/*
* Install a SurfaceHolder.Callback so we get notified when the
* underlying surface is created and destroyed.
*/
surfaceHolder = cameraPreview.getHolder();
surfaceHolder.addCallback(this);
/* deprecated setting, but required on Android versions prior to 3.0 */
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
private void showCamera() {
/* create an instance of Camera */
setCamera(getCameraInstance(currentCameraID));
}
private void setCamera(Camera camera) {
if (camera == this.camera) {
return;
}
this.camera = camera;
if (camera != null) {
/* set the camera display orientation */
setCameraDisplayOrientation(CameraActivity.this, currentCameraID,
camera);
// get Camera parameters
Camera.Parameters params = camera.getParameters();
List<String> focusModes = params.getSupportedFocusModes();
if (focusModes != null) {
if (focusModes
.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
// set the focus mode
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
camera.setParameters(params);
}
}
try {
camera.setPreviewDisplay(surfaceHolder);
} catch (IOException e) {
Log.i("IOException", e.getMessage());
}
// Important: Call startPreview() to start updating the preview
// surface. Preview must be started before you can take a picture.
camera.startPreview();
}
}
/* A safe way to get an instance of the Camera object. */
private Camera getCameraInstance(int cameraID) {
Camera camera = null;
try {
/* attempt to get a Camera instance */
camera = Camera.open(cameraID);
} catch (Exception e) {
/* Camera is not available (in use or does not exist) */
Log.i("CameraActivity", "Error getting camera: " + e.getMessage());
finish();
}
/* returns null if camera is unavailable */
return camera;
}
/* SurfaceHolder.Callback interface methods */
@Override
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the
// preview.
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (IOException e) {
Log.d("CameraActivity",
"Error setting camera preview: " + e.getMessage());
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (holder.getSurface() == null) {
// preview surface does not exist
Log.d("CameraActivity", "SurfaceHolder is null");
return;
}
// stop preview before making changes
try {
camera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
Log.d("CameraActivity",
"Error stopping camera preview: " + e.getMessage());
}
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (Exception e) {
Log.d("CameraActivity",
"Error starting camera preview: " + e.getMessage());
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// Take care of releasing the Camera preview in your activity.
if (camera != null) {
camera.stopPreview();
camera.release();
}
}
/* Camera.PictureCallback interface method */
@Override
public void onPictureTaken(byte[] data, Camera camera) {
// save the image asynchronously here
}
}
图片拍完后,要异步保存图片:
private class SaveImageTask extends AsyncTask<byte[], Void, Void> {
@Override
protected Void doInBackground(byte[]... data) {
FileOutputStream outStream = null;
// Write to SD Card
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/camtest");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
outStream.write(data[0]);
outStream.flush();
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length + " to " + outFile.getAbsolutePath());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return null;
}
}
我正在尝试制作一个 android 应用程序,它可以打开相机、启动计时器并在相机上显示计时器(当前时间,每秒刷新一次)。
我设法制作了一个计时器,我设法启动了相机,但我无法弄清楚如何以及在何处添加计时器数据。
我通过单击按钮启动相机,代码如下所示:
public void onClick(View v) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, IMAGE_CAPTURE);
}
我的计时器 class 此刻在 TextView 上打印数据,如下所示:
runOnUiThread(new Runnable(){
@Override
public void run() {
textCounter.setText(strDate);
}});
如有任何帮助,我们将不胜感激!
this github link 上有一个自定义相机 class 的示例。
我会尝试在下面解释您需要做什么。
对于您的布局,您可以使用此代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="@+id/cameraPreview"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" >
<TextView
android:id="@+id/timerTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:gravity="center"
android:layout_gravity="center" /> </FrameLayout> </LinearLayout>
将以下权限添加到您的清单中:
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
创建相机 activity 并预览 class:
public class CameraActivity extends Activity implements Camera.PictureCallback,
SurfaceHolder.Callback {
private Camera camera;
private SurfaceView cameraPreview;
private FrameLayout frameLayoutCameraPreview;
private int currentCameraID = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_camera);
cameraPreview = new SurfaceView(this);
cameraPreview.setKeepScreenOn(true);
initFormElements();
/* get the current camera id */
currentCameraID = Camera.CameraInfo.CAMERA_FACING_BACK;
/* show the camera */
showCamera();
}
@SuppressWarnings("deprecation")
private void initFormElements() {
frameLayoutCameraPreview = (FrameLayout) findViewById(R.id.cameraPreview);
// initialize your textview here as well
/* configure surface holder */
/*
* Install a SurfaceHolder.Callback so we get notified when the
* underlying surface is created and destroyed.
*/
surfaceHolder = cameraPreview.getHolder();
surfaceHolder.addCallback(this);
/* deprecated setting, but required on Android versions prior to 3.0 */
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
private void showCamera() {
/* create an instance of Camera */
setCamera(getCameraInstance(currentCameraID));
}
private void setCamera(Camera camera) {
if (camera == this.camera) {
return;
}
this.camera = camera;
if (camera != null) {
/* set the camera display orientation */
setCameraDisplayOrientation(CameraActivity.this, currentCameraID,
camera);
// get Camera parameters
Camera.Parameters params = camera.getParameters();
List<String> focusModes = params.getSupportedFocusModes();
if (focusModes != null) {
if (focusModes
.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
// set the focus mode
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
camera.setParameters(params);
}
}
try {
camera.setPreviewDisplay(surfaceHolder);
} catch (IOException e) {
Log.i("IOException", e.getMessage());
}
// Important: Call startPreview() to start updating the preview
// surface. Preview must be started before you can take a picture.
camera.startPreview();
}
}
/* A safe way to get an instance of the Camera object. */
private Camera getCameraInstance(int cameraID) {
Camera camera = null;
try {
/* attempt to get a Camera instance */
camera = Camera.open(cameraID);
} catch (Exception e) {
/* Camera is not available (in use or does not exist) */
Log.i("CameraActivity", "Error getting camera: " + e.getMessage());
finish();
}
/* returns null if camera is unavailable */
return camera;
}
/* SurfaceHolder.Callback interface methods */
@Override
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the
// preview.
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (IOException e) {
Log.d("CameraActivity",
"Error setting camera preview: " + e.getMessage());
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (holder.getSurface() == null) {
// preview surface does not exist
Log.d("CameraActivity", "SurfaceHolder is null");
return;
}
// stop preview before making changes
try {
camera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
Log.d("CameraActivity",
"Error stopping camera preview: " + e.getMessage());
}
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (Exception e) {
Log.d("CameraActivity",
"Error starting camera preview: " + e.getMessage());
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// Take care of releasing the Camera preview in your activity.
if (camera != null) {
camera.stopPreview();
camera.release();
}
}
/* Camera.PictureCallback interface method */
@Override
public void onPictureTaken(byte[] data, Camera camera) {
// save the image asynchronously here
}
}
图片拍完后,要异步保存图片:
private class SaveImageTask extends AsyncTask<byte[], Void, Void> {
@Override
protected Void doInBackground(byte[]... data) {
FileOutputStream outStream = null;
// Write to SD Card
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/camtest");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
outStream.write(data[0]);
outStream.flush();
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length + " to " + outFile.getAbsolutePath());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return null;
}
}