简体   繁体   中英

Effective method to convert an image file from RGB to YUV

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM