How to convert NV21 image format to bitmap?

I get preview data from the camera. It is in NV21 format. I want to save the preview on the ie SD card in a bitmap. My code receives the image and saves it, but in the gallery it is not captured by the preview. It is just a 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();
    }
}
+4
source share
1 answer

If you want to save the NV21 preview image for viewing in the gallery, the easiest way is to create YuvImage from the NV21 byte array and then compress it in JPEG to the file output stream, for example, 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();

, , , .

0

All Articles