【问题标题】:encode and decode bitmap to byte array without compress将位图编码和解码为字节数组而不压缩
【发布时间】:2014-09-14 15:29:30
【问题描述】:

我正在尝试在不使用 bitmap.compress 的情况下将位图编码和解码为字节数组,但是当我解码数组时,BitmapFactory.decodeByteArray 始终返回 NULL

编码方式如下:

public byte[] ToArray(Bitmap b)
{
    int bytes = b.getByteCount();

    ByteBuffer buffer = ByteBuffer.allocate(bytes); //Create a new buffer
    b.copyPixelsToBuffer(buffer); //Move the byte data to the buffer

    // DECODE
    String imgString = Base64.encodeToString(buffer.array(), Base64.NO_WRAP);
    byte[] ret = Base64.decode(imgString, Base64.DEFAULT);
    imgString = null;

    return ret;
}

有什么帮助吗?

【问题讨论】:

  • 为什么不使用 100% 质量的压缩?我假设这里关心的是图像的质量?
  • @Ali 如果您已经有效地创建了位图并打算将其存储在数据库中,那么再次压缩它是多余的。

标签: android bitmap base64 bytearray


【解决方案1】:

BitmapFactory 解码压缩的 jpeg。如果您想使用原始像素进行操作(就像使用 b.copyPixelsToBuffer(buffer); 一样,我建议您使用伴随方法 Bitmap.copyPixelsFromBuffer(buffer) 来恢复位图(我想您需要为此分配新的可变位图)

附:未压缩的图像比压缩的图像消耗更多的内存

【讨论】:

    【解决方案2】:

    试试这个:

    final int lnth=bitmap.getByteCount();
    ByteBuffer dst= ByteBuffer.allocate(lnth);
    bitmap.copyPixelsToBuffer( dst);
    byte[] barray=dst.array();
    

    走另一条路

    Bitmap bitmap = new BitmapFactory().decodeByteArray(byte_array, 0/* starting index*/, byte_array.length/*no of byte to read*/)
    

    【讨论】:

    • 这正是我所做的,我总是从 BitmapFactory.decodeByteArray 获得 null
    • 下载源代码并单步执行以查看发生了什么。很难从所提供的细节中说出问题所在。可能是位图的问题。
    • 看看这篇文章,看看它是否有帮助。 stackoverflow.com/questions/11411209/…
    • 因为BitmapFactory需要压缩图片数据,所以这个不行
    猜你喜欢
    • 2011-07-11
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    相关资源
    最近更新 更多