不压缩的情况下将位图编码和解码为字节数组

4
我会尽力协助您进行翻译。以下是需要翻译的内容:

我正在尝试将位图编码和解码为字节数组,但不使用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
@Ali 如果您已经成功创建了位图并打算存储它,比如在数据库中,再次压缩它就是多余的。 - Abandoned Cart
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*/)

2
这正是我所做的,但我总是从BitmapFactory.decodeByteArray得到null。 - L.Grillo
下载源代码并逐步查看以了解情况。很难从提供的详细信息来确定问题可能是什么。可能是位图的问题。 - Ali
看一下这篇帖子,看看它是否有帮助。http://stackoverflow.com/questions/11411209/bitmapfactory-decodestream-cannot-decode-png-type-from-ftp - Ali
3
因为BitmapFactory需要压缩的图像数据,所以这样做不起作用。 - marchinram

2

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接