我对 Android 4.0.x 的预览回调有疑问。我设置了一个摄像头,创建了一个显示摄像头图像on previewCallback
事件的表面。一切正常。
但在 Android 4.0.x 中,既不onPreviewCallback
调用也不调用onPreviewCallbackWithBuffer
. 这个问题有解决方法吗?
我想截屏并且不想使用takePicture()
-way,因为它会在短时间内冻结实时图像。
您必须在surfaceChanged 方法中调用setPreviewCallback,而不仅仅是在surfaceCreated 中。
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
if (mHolder.getSurface() == null){
return;
}
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
try {
mCamera.setPreviewCallback(this);
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
你可以调用 setOneShotPreviewCallback
mCamera.setOneShotPreviewCallback(new Camera.PreviewCallback() {
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
Camera.Parameters parameters = camera.getParameters();
int format = parameters.getPreviewFormat();
//YUV formats require more conversion
if (format == ImageFormat.NV21 || format == ImageFormat.YUY2 || format == ImageFormat.NV16) {
int w = parameters.getPreviewSize().width;
int h = parameters.getPreviewSize().height;
// Get the YuV image
YuvImage yuv_image = new YuvImage(data, format, w, h, null);
// Convert YuV to Jpeg
Rect rect = new Rect(0, 0, w, h);
ByteArrayOutputStream output_stream = new ByteArrayOutputStream();
yuv_image.compressToJpeg(rect, 100, output_stream);
byte[] byt = output_stream.toByteArray();
FileOutputStream outStream = null;
try {
// Write to SD Card
File file = createFileInSDCard(FOLDER_PATH, "Image_"+System.currentTimeMillis()+".jpg");
//Uri uriSavedImage = Uri.fromFile(file);
outStream = new FileOutputStream(file);
outStream.write(byt);
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
我也有类似的问题。PreviewCallbackWithBuffet
我在相机准备好之前进行了初始化。为了解决这个问题,我使用了以下代码:
_camera.addCallbackBuffer(createPreviewBuffer(new Size(width, height)));
_camera.setPreviewCallbackWithBuffer(new Camera.PreviewCallback() {
@Override
public void onPreviewFrame(byte[] bytes, Camera camera) {
processingRunnable.setNextFrame(bytes, camera))
}
});
_camera.startPreview();
希望能帮助到你