How to convert NV21 image format in bitmap?
Asked Answered
C

1

6

I am getting preview data from camera. It is in NV21 format. I want to save the preview to SD Card i.e in bitmap. My code is getting image and saving it, but in the gallery it is not captured preview. It is just black rectangle, Here is the code.

    public void processImage() {

    Bitmap bitmap = null;

    if (flag == true) {

        flag = false;

        if (mCamera != null) {

            Camera.Parameters parameters = mCamera.getParameters();

            int imageFormat = parameters.getPreviewFormat();

            if (imageFormat == ImageFormat.NV21) {
                Toast.makeText(mContext, "Format: NV21", Toast.LENGTH_SHORT)
                        .show();
                int w = parameters.getPreviewSize().width;
                int h = parameters.getPreviewSize().height;

                YuvImage yuvImage = new YuvImage(mData, imageFormat, w, h,
                        null);

                Rect rect = new Rect(0, 0, w, h);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();

                yuvImage.compressToJpeg(rect, 100, baos);

                byte[] jData = baos.toByteArray();

                bitmap = BitmapFactory.decodeByteArray(jData, 0,
                        jData.length);
            }

            else if (imageFormat == ImageFormat.JPEG
                    || imageFormat == ImageFormat.RGB_565) {

                Toast.makeText(mContext, "Format: JPEG||RGB_565",
                        Toast.LENGTH_SHORT).show();
                bitmap = BitmapFactory.decodeByteArray(mData, 0,
                        mData.length);
            }
        }

        if (bitmap != null) {
            saveImage(bitmap);
            Toast.makeText(mContext, "Image Saved", Toast.LENGTH_SHORT)
                    .show();
        } else
            Toast.makeText(mContext, "Bitmap Null", Toast.LENGTH_SHORT)
                    .show();
    }
}
Coastland answered 2/9, 2014 at 10:8 Comment(1)
have you found a solution for this?Johan
M
0

If you want to save the NV21 preview image to view in the gallery the easiest way is to create an YuvImage from the NV21 byte array and then compress it to a JPEG in a file output stream, like the code below:

FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory() + "/imagename.jpg");
YuvImage yuvImage = new YuvImage(nv21bytearray, ImageFormat.NV21, width, height, null);
yuvImage.compressToJpeg(new Rect(0, 0, width, height), 100, fos);
fos.close();

Please note that you probably want to change the path to save the image.

Muhammad answered 26/9, 2015 at 5:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.