3

I am developing an Android application project using Java. I have an image whose extension is JPG or BMP in RGB color space.

I want to convert it from RGB to YUV. I have googled and found that we can achieve it by using the brute force method of using a formula. However, speed is too slow as my application is a mobile application. Is there any other more effective method to convert it?

Ram
  • 3,092
  • 10
  • 40
  • 56
user3714221
  • 31
  • 1
  • 5

1 Answers1

6

This is how you convert from RGB to YUV

I didn't test how quick this is, but it should work fine

...

Bitmap b = ...
int bytes = b.getByteCount();
ByteBuffer buffer = ByteBuffer.allocate(bytes);
b.copyPixelsToBuffer(buffer); //Move the byte data to the buffer

byte[] data = buffer.array(); //Get the bytes array of the bitmap
YuvImage yuv = new YuvImage(data, ImageFormat.NV21, size.width, size.height, null);

Then do what you want with the YuvImage yuv.

And this is how to convert from YUV to RGB

ByteArrayOutputStream out = new ByteArrayOutputStream();
YuvImage yuv = new YuvImage(data, ImageFormat.NV2,size.width, size.height, null);
//data is the byte array of your YUV image, that you want to convert
yuv.compressToJpeg(new Rect(0, 0, size.width,size.height), 100, out);
byte[] bytes = out.toByteArray();

Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
  • After i follow ur step converrt YUV to JPg . I get a YuvImage object and I used yuv.compressToJpeg(new Rect(0,0,bitmap.getWidth(),bitmap.getHeight()), 0, fos); – user3714221 Jun 06 '14 at 09:04
  • to save output image. The result image is not full but the resolutio the same as origial bitmap. – user3714221 Jun 06 '14 at 09:05
  • By not full do you mean the picture was cut? –  Jun 06 '14 at 09:09
  • Yes, the picture was cut. What do you mean by size.width, size.height? is it the b.getWidth and b.getHeight? – user3714221 Jun 06 '14 at 15:40
  • Yes, this is the original bitmap's width and height. replace size.width with b.getWidth() and size.height with b.getHeight(). Let me know if everything works –  Jun 06 '14 at 17:56
  • Is the picture coming from the camera? If so, make sure that your rotation is correct. to do this, switch the width and height positions when converting to JPG: put b.getHeight() where size.width is and b.getWidth() where size.height is –  Jun 07 '14 at 11:43
  • @Eran I corrected the question title, can you approve my review? http://stackoverflow.com/review/suggested-edits/9114419 – jonathanrz Aug 10 '15 at 20:52