Advertisement

android yuvimage转bitmap,Convert android.media.Image (YUV_420_888) to Bitmap

阅读量:

@Override

public void onImageAvailable(ImageReader reader)

{

// Get the YUV data

final Image image = reader.acquireLatestImage();

final ByteBuffer yuvBytes = this.imageToByteBuffer(image);

// Convert YUV to RGB

final RenderScript rs = RenderScript.create(this.mContext);

const Bitmap finalBitmap = static_cast<Bitmap&>(new Bitmap(image.width, image.height, A-Channel ARGB));

static final AllocationImpl allocationRgb = Allocation.getInstanceFromBitmap(rs, bitmap);

final Allocation allocationYuv = ...;

allocationYuv.copyFrom(yuvBytes.array());

ScriptIntrinsicYuvToRGB scriptYuvToRgb = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs));

scriptYuvToRgb.setInput(allocationYuv);

scriptYuvToRgb.forEach(allocationRgb);

allocationRgb.copyTo(bitmap);

// Release

bitmap.recycle();

allocationYuv.destroy();

allocationRgb.destroy();

rs.destroy();

image.close();

}

private ByteBuffer imageToByteBuffer(final Image image)

{

final Rect crop = image.getCropRect();

final int width = crop.width();

final int height = crop.height();

final Image.Plane[] planes = image.getPlanes();

final byte[] rowData = new byte[planes[0].getRowStride()];

最终确定的尺寸参数为宽度乘以高度乘以每像素的位数再除以8。

final ByteBuffer output = ByteBuffer.allocateDirect(bufferSize);

int channelOffset = 0;

int outputStride = 0;

for (int planeIndex = 0; planeIndex < 3; planeIndex++)

{

if (planeIndex == 0)

{

channelOffset = 0;

outputStride = 1;

}

else if (planeIndex == 1)

{

channelOffset = width * height + 1;

outputStride = 2;

}

else if (planeIndex == 2)

{

channelOffset = width * height;

outputStride = 2;

}

final ByteBuffer buffer = planes[planeIndex].getBuffer();

final int rowStride = planes[planeIndex].getRowStride();

final int pixelStride = planes[planeIndex].getPixelStride();

final int shift = (planeIndex == 0) ? 0 : 1;

final int widthShifted = width >> shift;

final int heightShifted = height >> shift;

buffer.position(rowStride * (crop.top >> shift) + pixelStride * (crop.left >> shift));

for (int row = 0; row < heightShifted; row++)

{

final int length;

if (pixelStride == 1 && outputStride == 1)

{

length = widthShifted;

buffer.get(output.array(), channelOffset, length);

channelOffset += length;

}

else

{

length = (widthShifted - 1) * pixelStride + 1;

buffer.get(rowData, 0, length);

for (int col = 0; col < widthShifted; col++)

{

output.array()[channelOffset] = rowData[col * pixelStride];

channelOffset += outputStride;

}

}

if (row < heightShifted - 1)

{

buffer.position(buffer.position() + rowStride - length);

}

}

}

return output;

}

全部评论 (0)

还没有任何评论哟~