(Android) 如何直接从资产中的 png/jpg 图像中获取 RGB ByteBuffer?

问题描述

我尝试了几种方法来从 192 * 144 图像中获取正确的字节缓冲区,其中包含每个像素的 rgb 数据。 最终,我能够使用 double for 语句来获取值,但仍然很好奇。

这是我的代码

 fun getInputimage(): ByteBuffer {
    val fileInputStream = applicationContext.assets.open("input/onep_2.png")
    val image = BitmapFactory.decodeStream(fileInputStream)

    val input = ByteBuffer.allocateDirect(192 * 144 * 3)
            .order(ByteOrder.nativeOrder())

    for (j in 0 until image.height) {
        for (i in 0 until image.width) {
            val color = image.getPixel(i,j)
            val r = Color.red(color)
            val g = Color.green(color)
            val b = Color.blue(color)
            input.put(r.toByte())
            input.put(g.toByte())
            input.put(b.toByte())
        }
    }
    image.recycle()
    return input
}

fun getInputimage2(): ByteBuffer {
    val inputStream = applicationContext.assets.open("input/onep_2.png")
    val bos = ByteArrayOutputStream()
    val bytes = ByteArray(110592)
    while (true) {
        val br = inputStream.read(bytes)
        if (br == -1) break
        bos.write(bytes,br)
    }
    return ByteBuffer.wrap(bos.toByteArray())
}

fun getInputimage3(): ByteBuffer {
    val inputStream = applicationContext.assets.open("input/onep_2.png")
    val image = BitmapFactory.decodeStream(inputStream)
    val bos = ByteArrayOutputStream()
    image.compress(Bitmap.CompressFormat.PNG,100,bos)
    val bytes = bos.toByteArray()
    return ByteBuffer.wrap(bytes)
}

fun getInputimage4(): ByteBuffer {
    val stream = applicationContext.assets.open("input/onep_2.png")
    val fileBytes = ByteArray(stream.available())
    stream.read(fileBytes)
    stream.close()
    return ByteBuffer.wrap(fileBytes)
}

正确的 ByteBuffer 仅从第一个函数中获得, 并且下面所有函数的 ByteBuffer 大小比我想象的要小得多。

我的猜测是png/jpg的bits和bitmap的像素信息存储方式不同,所以好像没有得到想要的结果。 但我不确定这个猜测是否正确,所以我在问。

也在'getInputimage3()'中,我得到了最小的ByteBuffer。 即使将质量设置为 100,压缩函数是否也产生了这种结果?

最后,如何在不经过for语句的情况下得到与第一个函数相同的结果?

如果我的英语不够好,无法阅读,我深表歉意。 并提前感谢回答问题的人。

解决方法

png 是一个压缩的位图文件,当它原样放入字节缓冲区时,rgb 数据出不来..

我太笨了...