android - (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, 0, 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 的位存储方式与位图的像素信息不同,因此似乎没有得到想要的结果。但我不确定这个猜测是否正确,所以我在问。
同样在'getInputImage3()'中,我得到了最小的ByteBuffer。即使质量设置为 100,压缩功能是否产生了这个结果?
最后,如何在不通过 for 语句的情况下获得与第一个函数相同的结果?
如果我的英语不够好阅读,我深表歉意。并提前感谢会回答的人。
解决方案
png 是压缩的位图文件,当它按原样放入字节缓冲区时,rgb 数据无法出来。
我犯傻了...
推荐阅读
- google-chrome-extension - 从 chrome 扩展访问 react devtools `$r`
- javascript - 函数返回无效值
- java - 使用 Boxable 在同一 PDF 页面上放置文本和表格时出现问题
- javascript - 谁配置了 vim 编辑器来突出显示 ejs 语法?
- javascript - 开关功能乱序多次输出
- java - 在我的设备上获取当前位置时出错
- django - 在 Django 视图中重新组合模型中的数据
- javascript - 在用作边框源的 SVG 中悬停时启动 CSS 动画
- java - 使用 JFrame 形式 (Java) 中的缓冲写入器打印 ArrayList
- python - 熊猫分组错误重复轴但没有重复值