MediaCodec的解码流程这里就不做分析了。
主要分析outputbuffer拿到数据以后的问题。
outputbuffer有两种(只可取其一)可用的资源,一种是数据流,也就是byte[]存储的,yuv格式的数据,而bitmap需要的是rgb格式的数据。
所以取另一种,image存储的数据,
image = mediaCodec.getOutputImage(outIndex);
拿到image之后,
YuvImage yuvImage = new YuvImage(YUV_420_888toNV21(image), ImageFormat.NV21, width,height, null);
private static byte[] YUV_420_888toNV21(Image image) {
byte[] nv21;
ByteBuffer yBuffer = image.getPlanes()[0].getBuffer();
ByteBuffer uBuffer = image.getPlanes()[1].getBuffer();
ByteBuffer vBuffer = image.getPlanes()[2].getBuffer();
int ySize = yBuffer.remaining();
int uSize = uBuffer.remaining();
int vSize = vBuffer.remaining();
nv21 = new byte[ySize + uSize + vSize];
//U and V are swapped
yBuffer.get(nv21, 0, ySize);
vBuffer.get(nv21, ySize, vSize);
uBuffer.get(nv21, ySize + vSize, uSize);
return nv21;
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yuvImage.compressToJpeg(new Rect(0, 0, width, height), 80, stream);
bitmap = BitmapFactory.decodeByteArray(stream.toByteArray(), 0, stream.size());
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
这样就完成了yuv->bitmap.
PS:可以直接使用,想知其然又想知其所以然,可以私信我。