Android CameraX 와 TensorFlow Lite 사용하면서 ...
fun ByteArray.toBitmap(): Bitmap? {
return BitmapFactory.decodeByteArray(this, 0, this.size)
}
fun Image.toBitmap(): Bitmap {
val yBuffer = planes[0].buffer // Y
val vuBuffer = planes[2].buffer // VU
val ySize = yBuffer.remaining()
val vuSize = vuBuffer.remaining()
val nv21 = ByteArray(ySize + vuSize)
yBuffer.get(nv21, 0, ySize)
vuBuffer.get(nv21, ySize, vuSize)
val yuvImage = YuvImage(nv21, ImageFormat.NV21, this.width, this.height, null)
val out = ByteArrayOutputStream()
yuvImage.compressToJpeg(Rect(0, 0, yuvImage.width, yuvImage.height), 50, out)
val imageBytes = out.toByteArray()
return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
}
val matrix = Matrix().apply {
postRotate(90F)
}
val createBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, false)
private fun cropImage(bitmap: Bitmap, cameraPreview: View, innerView: View): ByteArray {
val heightOriginal = cameraPreview.height // preview height
val widthOriginal = cameraPreview.width // preview width
val heightFrame = innerView.height
val widthFrame = innerView.width
val heightReal = bitmap.height
val widthReal = bitmap.width
val widthFinal = widthFrame * widthReal / widthOriginal
val heightFinal = heightFrame * heightReal / heightOriginal
val maxX = cameraPreview.width - innerView.width
val maxY = cameraPreview.height - innerView.height
val leftFrame = if (innerView.x.toInt() < 0) {
0
} else if (innerView.x.toInt() > maxX) {
maxX
} else {
innerView.x.toInt()
}
val topFrame = if (innerView.y.toInt() < 0) {
0
} else if (innerView.y.toInt() > maxY) {
maxY
} else {
innerView.y.toInt()
}
val bitmapFinal = Bitmap.createBitmap(
bitmap,
leftFrame, topFrame, widthFinal, heightFinal
)
val stream = ByteArrayOutputStream()
bitmapFinal.compress(
Bitmap.CompressFormat.JPEG,
100,
stream
) //100 is the best quality possible
return stream.toByteArray()
}