将图像文件从RGB转换为YUV的有效方法

3

我正在使用Java开发一个Android应用程序项目。 我有一张图像,其扩展名为JPG或BMP,颜色空间为RGB。

我希望将其从RGB转换为YUV。 我已经搜索过并发现我们可以通过使用公式的暴力方法来实现它。 然而,由于我的应用程序是移动应用程序,速度太慢了。 有没有其他更有效的方法来转换它?

1个回答

6

这是如何从RGB转换到YUV的方法

我没有测试过这个方法的速度,但它应该可以正常工作。

...

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

然后您可以根据需要处理 YuvImage yuv。

以下是如何将YUV转换为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);

在我按照您的步骤将YUV转换为JPG后,我得到了一个YuvImage对象,并使用yuv.compressToJpeg(new Rect(0,0,bitmap.getWidth(),bitmap.getHeight()), 0, fos)。 - user3714221
你所说的“不完整”,是指图片被裁剪了吗? - user2213590
是的,图片被裁剪了。你说的size.width和size.height是指b.getWidth和b.getHeight吗? - user3714221
是的,这是原始位图的宽度和高度。将size.width替换为b.getWidth(),将size.height替换为b.getHeight()。如果一切正常,请告诉我。 - user2213590
@Eran,我已经更正了问题标题,你能批准我的审核吗?http://stackoverflow.com/review/suggested-edits/9114419 - jonathanrz
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接