我使用支持库中的ScriptIntrinsicYuvToRGB将图像从NV21格式转换为Bitmaps(ARGB_8888)时出现问题。下面的代码可以说明问题。使用ScriptIntrinsicYuvToRGB(支持lib)NV21到位图时损坏的图像
假设我有以下50×50图像(下面的一个是从装置的屏幕截图,实际上不是50×50):
然后,如果我转换所述图像以通过YuvImage#compressToJpeg
+ BitmapFactory.decodeByteArray
一个位图:
YuvImage yuvImage = new YuvImage(example, android.graphics.ImageFormat.NV21, width, height, null);
ByteArrayOutputStream os = new ByteArrayOutputStream();
yuvImage.compressToJpeg(new Rect(0, 0, width, height), 100, os);
byte[] jpegByteArray = os.toByteArray();
return BitmapFactory.decodeByteArray(jpegByteArray, 0, jpegByteArray.length);
我得到了预期的图像。但是,如果我把它转换通过ScriptIntrinsicYuvToRGB如下:
RenderScript rs = RenderScript.create(context);
Type.Builder tb = new Type.Builder(rs, Element.createPixel(rs,
Element.DataType.UNSIGNED_8, Element.DataKind.PIXEL_YUV));
tb.setX(width);
tb.setY(height);
tb.setYuvFormat(android.graphics.ImageFormat.NV21);
Allocation yuvAllocation = Allocation.createTyped(rs, tb.create(), Allocation.USAGE_SCRIPT);
yuvAllocation.copyFrom(example);
Type rgbType = Type.createXY(rs, Element.RGBA_8888(rs), width, height);
Allocation rgbAllocation = Allocation.createTyped(rs, rgbType);
ScriptIntrinsicYuvToRGB yuvToRgbScript = ScriptIntrinsicYuvToRGB.create(rs, Element.RGBA_8888(rs));
yuvToRgbScript.setInput(yuvAllocation);
yuvToRgbScript.forEach(rgbAllocation);
Bitmap convertedBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
rgbAllocation.copyTo(convertedBitmap);
我得到以下损坏的图像:
我已经注意到这种情况的发生与方形尺寸的图像,且从未2的幂(例如64x64,128x128等)。如果我没有尝试方形尺寸,我不会注意到这个问题,因为一些图片尺寸(如2592x1728)可以正常工作。我错过了什么?
更新:将生成原始图像的要求代码:
int width = 50;
int height = 50;
int size = width * height;
byte[] example = new byte[size + size/2];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
example[y * width + x] = (byte) ((x*y/(float)size) * 255);
}
}
for (int i = 0; i < size/2; i++) {
example[size + i] = (byte) (127);
}
你能后的输入文件,它可以用来测试你的代码?重现错误有点困难,否则。 :) – cmaster11
@ cmaster11我做得比这更好,我只是在问题的末尾添加了生成输入图像的代码:) – silvaren