Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 425
Hongwei Yan Avatar asked Jul 31 '10 03:07

Hongwei Yan


2 Answers

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

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

like image 80
user1553112 Avatar answered Nov 16 '22 06:11

user1553112


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:

Getting frames from Video Image in Android

Let me know if it works.

Cheers,

Paul

like image 45
paul_wong_ Avatar answered Nov 16 '22 05:11

paul_wong_