Skip to content

Instantly share code, notes, and snippets.

@farmaker47
Created April 17, 2021 05:48
Show Gist options
  • Save farmaker47/f5f9c87ddf81c305b4571f7d95d3646a to your computer and use it in GitHub Desktop.
Save farmaker47/f5f9c87ddf81c305b4571f7d95d3646a to your computer and use it in GitHub Desktop.
fun bitmapToByteBuffer(
bitmapIn: Bitmap,
width: Int,
height: Int,
mean: Float = 0.0f,
std: Float = 255.0f
): ByteBuffer {
//var bitmap = cropBitmap(bitmapIn)
//bitmap = scaleBitmapAndKeepRatio(bitmapIn, width, height)
val bitmap = Bitmap.createScaledBitmap(bitmapIn, width, height, true)
val inputImage = ByteBuffer.allocateDirect(1 * width * height * 3 * 4)
inputImage.order(ByteOrder.nativeOrder())
inputImage.rewind()
val intValues = IntArray(width * height)
bitmap.getPixels(intValues, 0, width, 0, 0, width, height)
var pixel = 0
for (i in 0 until 3) {
for (x in 0 until width) {
for (y in 0 until height) {
//val value = intValues[pixel++]
val value = intValues[x * width + y]
when (i) {
0 -> {
inputImage.putFloat(((Color.red(value)) - mean) / std)
}
1 -> {
inputImage.putFloat(((Color.green(value)) - mean) / std)
}
else -> {
inputImage.putFloat(((Color.blue(value)) - mean) / std)
}
}
}
}
}
return inputImage
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment