初始化相机
private void initCamera() {
setContentView(R.layout.main);
btnTake = (Button) this.findViewById(R.id.take);
btnTake.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
camera.autoFocus(new AutoFocusCallback());
}
});
Display display = getWindowManager().getDefaultDisplay();
surfaceView = (SurfaceView) this.findViewById(R.id.mSurfaceView1);
surfaceView.getHolder().setFixedSize(display.getWidth(),
display.getHeight()); // 设置分辨率
/* 下面设置Surface不维护自己的缓冲区,而是等待屏幕的渲染引擎将内容推送到用户面前 */
surfaceView.getHolder()
.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
surfaceView.getHolder().addCallback(new SurfaceCallback());
}
回调函数类
private final class SurfaceCallback implements SurfaceHolder.Callback {
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
camera = Camera.open();
Camera.Parameters parameters = camera.getParameters();
// parameters.setPreviewSize(1024, 768);//设置预览照片的大小
// parameters.setPreviewFrameRate(3);//每秒3帧
parameters.setPictureFormat(PixelFormat.JPEG);// 设置照片的输出格式
parameters.set("jpeg-quality", quality);// 照片质量
parameters.setPictureSize(photoWidth, photoHeight);// 设置照片的大小
parameters.set("orientation", "landscape");
// parameters.set("orientation", "portrait");
// parameters.set("rientation", "90");
// camera.setDisplayOrientation(90);
// parameters.set("rotation", "180");
// parameters.set("orientation", "landscape");
parameters.setRotation(180);
camera.setParameters(parameters);
camera.setPreviewDisplay(surfaceView.getHolder());// 通过SurfaceView显示取景画面
camera.startPreview();// 开始预览
preview = true;
} catch (IOException e) {
Log.e(TAG, e.toString());
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (camera != null) {
if (preview)
camera.stopPreview();
camera.release();
}
}
}
自动对焦
private final class AutoFocusCallback implements Camera.AutoFocusCallback {
@Override
public void onAutoFocus(boolean success, Camera camera) {
camera.takePicture(null, null, new TakePictureCallback());
}
}
拍照保存
private final class TakePictureCallback implements PictureCallback {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
data.length);
File file = new File(temPath);
FileOutputStream outStream = new FileOutputStream(file);
// Bitmap 旋转
Matrix vMatrix = new Matrix();
vMatrix.setRotate(270);
Bitmap vB2 = Bitmap.createBitmap(bitmap, 0, 0, bitmap
.getWidth() // 宽度
, bitmap.getHeight() // 高度
, vMatrix, true);
vB2.compress(CompressFormat.JPEG, 100, outStream);
outStream.close();
camera.stopPreview();
// savePhoto();
setReview();
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
}