Wednesday, February 27, 2013

Get Bitmap image from a YUV in Android


Android Camera preview image is in YUV format. The YUV byte[] will have gray image in the first width*height bytes and color information next. For processing preview image without taking picture from Camera using Camera.takePicture method, mostly we need to convert the YUV byte[] into a Bitmap. Following code will help do that


import java.io.ByteArrayOutputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;

public class Utils {

       public static Bitmap getBitmapImageFromYUV(byte[] data, int width, int height) {
              YuvImage yuvimage = new YuvImage(data, ImageFormat.NV21, width, height, null);
              ByteArrayOutputStream baos = new ByteArrayOutputStream();
              yuvimage.compressToJpeg(new Rect(0, 0, width, height), 80, baos);
              byte[] jdata = baos.toByteArray();
              BitmapFactory.Options bitmapFatoryOptions = new BitmapFactory.Options();
              bitmapFatoryOptions.inPreferredConfig = Bitmap.Config.RGB_565;
              Bitmap bmp = BitmapFactory.decodeByteArray(jdata, 0, jdata.length, bitmapFatoryOptions);
              return bmp;
       }

}

Blog Archive