When I am trying to convert a byte array in YUV format to a bitmap and then saving that into emulated storage the image appears to be corrupted.
First I transform the yuv image to jpeg, and decode to Bitmap
byte[] segments = Transform.YUVtoJPEG(yuv, obj.getInt("w"), obj.getInt("h"), 100);
Bitmap bitmap = BitmapFactory.decodeByteArray(segments, 0, segments.length);
saveBitmapToExternalStorage(bitmap);
Here is Transform.YUVtoJpeg
public static byte[] YUVtoJPEG(byte[] yuv, int ww, int hh, int jpegQuality) {
// compress yuv byte array to jpeg
final YuvImage yuvImage = new YuvImage(yuv, ImageFormat.NV21, ww, hh,null);
ByteArrayOutputStream outStream=new ByteArrayOutputStream();
yuvImage.compressToJpeg(new Rect(0, 0, ww, hh), jpegQuality, outStream);
return outStream.toByteArray();
}
And here is where I save the image
public static void saveBitmapToExternalStorage(Bitmap b){
try {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".png";
File file = new File (myDir, fname);
try {
FileOutputStream outF = new FileOutputStream(file);
b.compress(Bitmap.CompressFormat.PNG, 100, outF);
outF.close();
} catch (Exception e) {
Log.e("myTag", "NOT SAVED");
}
}
catch (Exception e){
Log.e("MyTag", "Nope");
}
}
Any advice is great, I'm quite stuck. Here are some examples of corrupted images enter image description here