Java – An efficient way to convert image files from RGB to YUV

An efficient way to convert image files from RGB to YUV… here is a solution to the problem.

An efficient way to convert image files from RGB to YUV

I’m developing an Android application project using Java. I have an image with an extension JPG or BMP in the RGB color space.

I want to convert it from RGB to YUV. I googled it a bit and found that we can do it by using the brute force method of formulas. However, since my app is a mobile app, it’s too slow. Are there other more efficient conversion methods?

Solution

This is how you convert RGB to YUV

I didn’t test how fast 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 YuvImage yuv.

That’s 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);

Related Problems and Solutions