首页 文章

编码和解码位图到字节数组而不压缩

提问于
浏览
3

我正在尝试编码和解码位图到字节数组而不使用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;
}

有帮助吗?

2 回答

  • 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*/)
    
  • 3

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

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

相关问题