如何在 Android 编程中从相机应用程序中捕获预览图像帧? [英] How to capture preview image frames from Camera Application in Android Programming?

查看:21
本文介绍了如何在 Android 编程中从相机应用程序中捕获预览图像帧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个应用程序来捕获相机预览帧并将其转换为 Android 中的位图.这是我的代码:

I am writing an app to capture the camera preview frames and convert it to bitmap in 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.

将字节数组转换为BitMap时我做错了什么?

What did I do wrong when convert the byte array to BitMap?

推荐答案

onPreviewFrame()函数中,首先要检查图片格式.
这是 NV21 示例.

In the onPreviewFrame() function, you should check the image format first.
This the NV21 example.

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();
        }
    }
}

有关其他拍照方式,请查看这篇文章:如何在android中使用相机

For another way to take pictures, check out this article: how to use camera in android

这篇关于如何在 Android 编程中从相机应用程序中捕获预览图像帧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆