如何在Android编程中从相机应用程序捕获预览图像帧?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3376672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to capture preview image frames from Camera Application in Android Programming?
提问by Hongwei Yan
I am writing an app to capture the camera preview frames and convert it to bitmap in Android. Here is my code:
我正在编写一个应用程序来捕获相机预览帧并将其转换为 Android 中的位图。这是我的代码:
Camera.PreviewCallback previewCallback = new Camera.PreviewCallback()
{
public void onPreviewFrame(byte[] data, Camera camera)
{
try
{
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);//,opts);
}
catch(Exception e)
{
}
}
};
mCamera = Camera.open();
mCamera.setPreviewCallback(previewCallback);
After I start preview, the callback got called with data, but the bitmap is null.
开始预览后,回调被数据调用,但位图为空。
What did I do wrong when convert the byte array to BitMap?
将字节数组转换为 BitMap 时我做错了什么?
回答by user1553112
In the onPreviewFrame()
function, you should check the image format first.
This the NV21 example.
在onPreviewFrame()
函数中,您应该先检查图像格式。
这是 NV21 示例。
public void onPreviewFrame(byte[] data, Camera camera)
{
Parameters parameters = camera.getParameters();
imageFormat = parameters.getPreviewFormat();
if (imageFormat == ImageFormat.NV21)
{
Rect rect = new Rect(0, 0, PreviewSizeWidth, PreviewSizeHeight);
YuvImage img = new YuvImage(data, ImageFormat.NV21, PreviewSizeWidth, PreviewSizeHeight, null);
OutputStream outStream = null;
File file = new File(NowPictureFileName);
try
{
outStream = new FileOutputStream(file);
img.compressToJpeg(rect, 100, outStream);
outStream.flush();
outStream.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
For another way to take pictures, check out this article: how to use camera in android
对于另一种拍照方式,请查看这篇文章:如何在android中使用相机
回答by paul_wong_
Have you tried decoding the preview frame data to RGB before you use BitmapFactory? The default format is YUV which I'm not sure is compatible with BitmapFactory. Dave Manpearl's decode method can be found here:
在使用 BitmapFactory 之前,您是否尝试过将预览帧数据解码为 RGB?默认格式是 YUV,我不确定它是否与 BitmapFactory 兼容。Dave Manpearl 的解码方法可以在这里找到:
Getting frames from Video Image in Android
Let me know if it works.
让我知道它是否有效。
Cheers,
干杯,
Paul
保罗