我尝试使用onPreviewFrame方法在服务中拍照。
我保存了一个.jpg文件,但是当我尝试打开该文件时却无法保存,因为图像已损坏。
这是我第一次使用API相机和surfaceTexture,我不知道是否需要添加一些配置或其他内容。
有想正确保存照片的想法吗?
服务代码为:
public class ServicioTextureCamara extends Service {
private final static String TAG = "CameraServiceTexture";
private Camera mCamera;
private Bitmap _currentFrame;
public static final String FACEDETECTIONTHREAD_TAG = "FaceDetectionThread_Tag";
@Override public int onStartCommand(Intent intent, int flags, int startId) {
new PictureThread().start();
return START_STICKY;
}
private class PictureThread extends Thread {
SurfaceTexture texture;
private byte[] callbackBuffer;
public void run() {
mCamera = CameraHelper.getCameraInstance();
texture = new SurfaceTexture(0);
texture.setDefaultBufferSize(4, 4);
try {
mCamera.setPreviewTexture(texture);
} catch (IOException e1) {
e1.printStackTrace();
}
Camera.Size previewSize=mCamera.getParameters().getPreviewSize();
int dataBufferSize=(int)(previewSize.height*previewSize.width*
(ImageFormat.getBitsPerPixel(mCamera.getParameters().getPreviewFormat())/8.0));
callbackBuffer = new byte[dataBufferSize];
mCamera.addCallbackBuffer(callbackBuffer);
mCamera.setPreviewCallbackWithBuffer(previewCallback);
mCamera.startPreview();
time = System.currentTimeMillis();
}
private int mMaxCount = 100;
private int mCount = 0;
private long time;
private final Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {
@Override public void onPreviewFrame(byte[] data, Camera camera) {
long currentTime = System.currentTimeMillis();
Log.i(TAG, "onPreviewFrame " + data.length + " " + (currentTime - time));
time = currentTime;
mCamera.addCallbackBuffer(callbackBuffer);
File pictureFileDir = getDir(Environment.DIRECTORY_PICTURES, Context.MODE_PRIVATE);
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
return;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "PictureFront_" + "_" + date + ".jpg";
String filename = pictureFileDir.getPath() + File.separator + photoFile;
File mainPicture = new File(filename);
try {
FileOutputStream fos = new FileOutputStream(mainPicture);
fos.write(data);
fos.close();
System.out.println("image saved");
} catch (Exception error) {
System.out.println("Image could not be saved");
}
}
};
}
}