Skip to content

Instantly share code, notes, and snippets.

@mebjas
Created September 29, 2019 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mebjas/ba655890daf8c3eb14409ee8cc71f9ae to your computer and use it in GitHub Desktop.
Save mebjas/ba655890daf8c3eb14409ee8cc71f9ae to your computer and use it in GitHub Desktop.
/**
* Converts the YUV420_888 Image into a packed NV21 of a single byte array,
* suitable for JPEG compression by the method convertNv21toJpeg. Creates a
* memory block with the y component at the head and interleaves the u,v
* components following the y component. Caller is responsible to allocate a
* large enough buffer for results.
*
* @param img image to be converted
* @param dataCopy buffer to write NV21 packed image
* @return byte array of NV21 packed image
*/
private byte[] convertYUV420ImageToPackedNV21(ImageProxy img, byte[] dataCopy) {
// Get all the relevant information and then release the image.
final int w = img.getWidth();
final int h = img.getHeight();
final ImageProxy.PlaneProxy[] planeList = img.getPlanes();
ByteBuffer y_buffer = planeList[0].getBuffer();
ByteBuffer u_buffer = planeList[1].getBuffer();
ByteBuffer v_buffer = planeList[2].getBuffer();
final int color_pixel_stride = planeList[1].getPixelStride();
Log.d(TAG, "Size of Y buffer: " +String.valueOf(y_buffer.capacity()));
Log.d(TAG, "Size of U buffer: " +String.valueOf(u_buffer.capacity()));
Log.d(TAG, "Size of V buffer: " +String.valueOf(v_buffer.capacity()));
Log.d(TAG, "Color Pixel Stride: " +String.valueOf(color_pixel_stride));
final int y_size = y_buffer.capacity();
final int u_size = u_buffer.capacity();
final int data_offset = w * h;
for (int i = 0; i < y_size; i++) {
dataCopy[i] = (byte) (y_buffer.get(i) & 255);
}
for (int i = 0; i < u_size / color_pixel_stride; i++) {
dataCopy[data_offset + 2 * i] = v_buffer.get(i * color_pixel_stride);
dataCopy[data_offset + 2 * i + 1] = u_buffer.get(i * color_pixel_stride);
}
return dataCopy;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment