I'm trying to convert a bitmap to YUV420 on Android, but I haven't been successful. Is it possible to convert it properly?
The code I'm using looks like this:
fun bitmapToYUV(bitmap: Bitmap): ByteArray {
val width = bitmap.width
val height = bitmap.height
val pixels = IntArray(width * height)
bitmap.getPixels(pixels, 0, width, 0, 0, width, height)
val byteArray = ByteArray(width * height * 3)
for (i in 0 until width * height) {
byteArray[i * 3] = (pixels[i] shr 16 and 0xFF).toByte()
byteArray[i * 3 + 1] = (pixels[i] shr 8 and 0xFF).toByte()
byteArray[i * 3 + 2] = (pixels[i] and 0xFF).toByte()
}
val yuvArray = ByteArray(width * height * 3 / 2)
convertYUV420SPtoYUV420P(byteArray, width, height, yuvArray)
return yuvArray
}
fun convertYUV420SPtoYUV420P(src: ByteArray, width: Int, height: Int, dst: ByteArray) {
val uvSize = width * height / 4
for (i in 0 until height) {
for (j in 0 until width) {
val y = src[i * width + j].toInt() and 0xFF
val u = src[width * height + (i / 2) * (width / 2) + (j / 2)].toInt() and 0xFF
val v =
src[width * height + uvSize + (i / 2) * (width / 2) + (j / 2)].toInt() and 0xFF
dst[i * width + j] = y.toByte()
dst[i * width + j + width] = (u - 128).toByte()
dst[i * width + j + width * 2] = (v - 128).toByte()
}
}
}