简体   繁体   English

如何从Android编程中的Camera Application捕获预览图像帧?

[英]How to capture preview image frames from Camera Application in Android Programming?

I am writing an app to capture the camera preview frames and convert it to bitmap in Android. 我正在编写一个应用程序来捕获相机预览帧并将其转换为Android中的位图。 Here is my code: 这是我的代码:

   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时,我做错了什么?

In the onPreviewFrame() function, you should check the image format first. onPreviewFrame()函数中,您应该首先检查图像格式。
This the NV21 example. 这是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中使用相机

Have you tried decoding the preview frame data to RGB before you use BitmapFactory? 在使用BitmapFactory之前,您是否尝试将预览帧数据解码为RGB? The default format is YUV which I'm not sure is compatible with BitmapFactory. 默认格式是YUV,我不确定它与BitmapFactory兼容。 Dave Manpearl's decode method can be found here: Dave Manpearl的解码方法可以在这里找到:

Getting frames from Video Image in Android 从Android中的视频图像中获取帧

Let me know if it works. 如果有效,请告诉我。

Cheers, 干杯,

Paul 保罗

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM