Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to save a preview frame as jpeg image?

Tags:

android

camera

I would like to save a preview frame as a jpeg image.

I have tried to write the following code:

public void onPreviewFrame(byte[] _data, Camera _camera)
{
    if(settings.isRecording())
    {
        Camera.Parameters params = _camera.getParameters();
        params.setPictureFormat(PixelFormat.JPEG);
        _camera.setParameters(params);
        String path = "ImageDir" + frameCount;
        fileRW.setPath(path);
        fileRW.WriteToFile(_data);
        frameCount++;
    }
}

but it's not possible to open a saved file as a jpeg image. Does anyone know how to save preview frames as jpeg images?

Thanks

like image 499
Niko Gamulin Avatar asked Jun 23 '09 12:06

Niko Gamulin


2 Answers

checkout this code. i hope it helps

camera.setPreviewCallback(new PreviewCallback() {
                    @Override
                    public void onPreviewFrame(byte[] data, Camera camera) {
                        // TODO Auto-generated method stub
                        Camera.Parameters parameters = camera.getParameters();
                        Size size = parameters.getPreviewSize();
                        YuvImage image = new YuvImage(data, ImageFormat.NV21,
                                size.width, size.height, null);
                        Rect rectangle = new Rect();
                        rectangle.bottom = size.height;
                        rectangle.top = 0;
                        rectangle.left = 0;
                        rectangle.right = size.width;
                        ByteArrayOutputStream out2 = new ByteArrayOutputStream();
                        image.compressToJpeg(rectangle, 100, out2);
                        DataInputStream in = new DataInputStream();
                        in.write(out2.toByteArray());

                        }
                    }

                });
                camera.startPreview();
like image 75
Dany's Avatar answered Nov 04 '22 00:11

Dany's


You have to convert it manually, there are some examples on the android-developers list if you browse the archive - mostly dealing with the format (luminance/chrominance,etc) conversion, then writing the image to a bitmap, then saving to a file.

It's all a bit of a pain really.

like image 35
piemmm Avatar answered Nov 03 '22 22:11

piemmm