将 Java 位图转换为字节数组
Bitmap bmp = intent.getExtras().get("data");
int size = bmp.getRowBytes() * bmp.getHeight();
ByteBuffer b = ByteBuffer.allocate(size);
bmp.copyPixelsToBuffer(b);
byte[] bytes = new byte[size];
try {
b.get(bytes, 0, bytes.length);
} catch (BufferUnderflowException e) {
// always happens
}
// do something with byte[]
当我在调用 copyPixelsToBuffer
后查看缓冲区时,字节全部为 0...从相机返回的位图是不可变的...但这应该不重要,因为它正在执行复制。
这段代码可能有什么问题?
Bitmap bmp = intent.getExtras().get("data");
int size = bmp.getRowBytes() * bmp.getHeight();
ByteBuffer b = ByteBuffer.allocate(size);
bmp.copyPixelsToBuffer(b);
byte[] bytes = new byte[size];
try {
b.get(bytes, 0, bytes.length);
} catch (BufferUnderflowException e) {
// always happens
}
// do something with byte[]
When I look at the buffer after the call to copyPixelsToBuffer
the bytes are all 0... The bitmap returned from the camera is immutable... but that shouldn't matter since it's doing a copy.
What could be wrong with this code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
尝试这样的事情:
Try something like this:
CompressFormat 太慢...
尝试 ByteBuffer。
※※※位图转字节数组※※※
※※※字节数组转位图※※※
CompressFormat is too slow...
Try ByteBuffer.
※※※Bitmap to Byte-array※※※
※※※Byte-array to Bitmap※※※
这是用 Kotlin 编写的位图扩展
.convertToByteArray
。Here is bitmap extension
.convertToByteArray
wrote in Kotlin.也许您需要倒带缓冲区?
此外,如果位图的步长(以字节为单位)大于行长度(以像素 * 字节/像素为单位),则可能会发生这种情况。将字节长度设置为 b.remaining() 而不是 size。
Do you need to rewind the buffer, perhaps?
Also, this might happen if the stride (in bytes) of the bitmap is greater than the row length in pixels * bytes/pixel. Make the length of bytes b.remaining() instead of size.
使用以下函数将位图编码为字节[],反之亦然
Use below functions to encode bitmap into byte[] and vice versa
你的字节数组太小了。每个像素占用 4 个字节,而不仅仅是 1 个字节,因此将您的大小乘以 4,以便数组足够大。
Your byte array is too small. Each pixel takes up 4 bytes, not just 1, so multiply your size * 4 so that the array is big enough.
Ted Hopp 是正确的,来自 API 文档:
“...此方法返回后,缓冲区的当前位置会更新:位置会根据写入缓冲区中的元素数量递增。
”
和
“将字节从当前位置读取到指定的字节数组中,从指定的偏移量开始,并将位置增加读取的字节数。”
Ted Hopp is correct, from the API Documentation :
"... After this method returns, the current position of the buffer is updated: the position is incremented by the number of elements written in the buffer.
"
and
"Reads bytes from the current position into the specified byte array, starting at the specified offset, and increases the position by the number of bytes read."
为了避免较大文件出现 OutOfMemory 错误,我建议通过将位图拆分为多个部分并合并各个部分的字节来解决该任务。
In order to avoid
OutOfMemory
error for bigger files, I would recommend to solve the task by splitting a bitmap into several parts and merging their parts' bytes.我想这会做 -
I think this will do -
尝试将字符串-位图或位图-字符串转换
Try this to convert String-Bitmap or Bitmap-String