YUV to JPG Conversion
Information | |
|---|---|
Description | Code snippet for converting an Android ImageReader YUV frame to a JPG image. |
Purpose | The function:
|
Language | Kotlin |
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
- A ByteArray containing the compressed JPG image.
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()
}Notes
- 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 desiredWidth allows 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.Toolkit dependency for the image conversion algorithm.