我使用支持庫中的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