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

时间:2014-07-23 12:34:49

标签: android bitmap base64 bytearray

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

答案 0 :(得分:3)

试试这个:

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

答案 1 :(得分:2)

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

P.S。未压缩的图像比压缩的内存消耗更多的内存

相关问题