| Information | |
|---|---|
| Description | Code snippet for converting an Android ImageReader YUV frame to a JPG image. |
| Purpose | The function: Converts raw YUV image data to an RGB Bitmap Scales it down to a predefined width (220 px) while maintaining aspect ratio Compresses the bitmap to JPEG (50% quality) Returns the result as a ByteArray |
| Language | Kotlin |
Input Parameters
Section titled “Input Parameters”- yuvBytes:
ByteArray
The raw YUV NV21 frame data (e.g., from a camera preview). - width:
Int
Width of the image in pixels. - height:
Int
Height of the image in pixels.
Output
Section titled “Output”- A
ByteArraycontaining the compressed JPG image.
Snippet
Section titled “Snippet”import com.google.android.renderscript.Toolkit// ...
fun convertYuvToJpeg( yuvBytes: ByteArray, width: Int, height: Int, quality: Int = 50, desiredWidth: Int = 220): ByteArray { val rgbBitmap = Toolkit.yuvToRgbBitmap(yuvBytes, width, height, YuvFormat.NV21).let { val bitmap = if (it.width > it.height) { val matrix = Matrix().apply { postRotate(-90f) } Bitmap.createBitmap(it, 0, 0, it.width, it.height, matrix, true) } else it
val desiredHeight = desiredWidth * bitmap.height / bitmap.width Bitmap.createScaledBitmap(bitmap, desiredWidth, desiredHeight, false) }
val outputStream = ByteArrayOutputStream() rgbBitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream) return outputStream.toByteArray()}- The JPG compression level (i.e.
quality) is adjustable. A lower value reduces the file size at the cost of image quality. Use 50% as an initial value. - The
desiredWidthallows to configure the size of the JPG image. We have set this to 220px as a good compromise between file size and image resolution. - The image transformation introduces a load on the system. It’s recommended to run this in a separate thread to avoid blocking the main thread and causing frame-drop while recording.
- This snippet uses the
com.google.android.renderscript.Toolkitdependency for the image conversion algorithm.

