安卓中实现静默拍照的代码
javaimport android.content.Context;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.File;
import java.io.IOException;
public class SilentCamera {
private Camera camera;
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
public SilentCamera(Context context) {
surfaceView = new SurfaceView(context);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.setFormat(PixelFormat.JPEG);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void startCamera() {
camera = Camera.open();
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}
public void takePhoto(String fileName) {
camera.takePicture(null, null, new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
File file = new File(fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void stopCamera() {
camera.stopPreview();
camera.release();
camera = null;
}
}
示例用法:
javaSilentCamera silentCamera = new SilentCamera(context); // 初始化相机
silentCamera.startCamera(); // 启动相机预览
silentCamera.takePhoto("photo.jpg"); // 拍照并保存为文件
silentCamera.stopCamera(); // 停止相机预览
输出结果:
在以上示例用法中,拍照后的图片文件会被保存在指定的文件名下。