Android中调用摄像头并自动对焦拍照
首先需要在Manifest文件中添加以下内容:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
程序获取摄像头使用以及自动对焦功能的使用权限。
CameraTestActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import
android.view.WindowManager;
public class CameraTestActivity extends
Activity {
@Override
publicvoid onCreate(Bundle
bundle) {
super.onCreate(bundle);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);// 设置横屏模式以及全屏模式
setContentView(new CameraView(this));//设置View
}
}
CameraView.java
import
java.io.FileOutputStream;
import android.content.Context;
import
android.hardware.Camera;
import
android.os.Environment;
import
android.view.MotionEvent;
import
android.view.SurfaceHolder;
import
android.view.SurfaceView;
public class CameraView extends SurfaceView implements
SurfaceHolder.Callback, Camera.PictureCallback {
private SurfaceHolder holder;
private Camera camera;
privateboolean af;
public CameraView(Context context) {//构造函数
super(context);
holder= getHolder();//生成Surface Holder
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);//指定Push Buffer
}
publicvoid surfaceCreated(SurfaceHolder
holder) {//Surface生成事件的处理
try {
camera= Camera.open();//摄像头的初始化
camera.setPreviewDisplay(holder);
}catch (Exception e) {
}
}
@Override
publicvoid surfaceChanged(SurfaceHolder
holder,int format,int width,int height) {//Surface改变事件的处理
Camera.Parameters parameters= camera.getParameters();
parameters.setPreviewSize(width,
height);
camera.setParameters(parameters);//设置参数
camera.startPreview();//开始预览
}
publicvoid surfaceDestroyed(SurfaceHolder
holder) {//Surface销毁时的处理
camera.setPreviewCallback(null);
camera.stopPreview();
camera.release();
camera= null;
}
@Override
publicboolean onTouchEvent(MotionEvent event) {//屏幕触摸事件
if (event.getAction()== MotionEvent.ACTION_DOWN) {//按下时自动对焦
camera.autoFocus(null);
af= true;
}
if (event.getAction()== MotionEvent.ACTION_UP&& af== true) {//放开后拍照
camera.takePicture(null,null,this);
af= false;
}
return true;
}
publicvoid onPictureTaken(byte[] data, Camera camera) {//拍摄完成后保存照片
try {
String path= Environment.getExternalStorageDirectory()+ "/test.jpg";
data2file(data, path);
}catch (Exception e) {
}
camera.startPreview();
}
privatevoid data2file(byte[] w, String fileName) throws Exception {//将二进制数据转换为文件的函数
FileOutputStream out= null;
try {
out= new FileOutputStream(fileName);
out.write(w);
out.close();
}catch (Exception e) {
if (out!= null)
out.close();
throw e;
}
}
}
说明:这是一个简单的示例程序。功能是使用自动对焦功能拍摄一张照片保存于SD卡根目录下。本例中许多参数都没有设置,可以根据具体需要进行适当的修改以满足特定要求。