将位图转换为字节数组 Android

51

我有一个位图,想通过将其编码为base64发送到服务器,但我不想压缩png或jpeg中的图像。

现在我之前所做的是:

ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream();
bitmapPicture.compress(Bitmap.CompressFormat.PNG, COMPRESSION_QUALITY, byteArrayBitmapStream);
byte[] b = byteArrayBitmapStream.toByteArray();
//then simple encoding to base64 and off to server
encodedImage = Base64.encodeToString(b, Base64.NO_WRAP);

现在我不想使用任何压缩或格式,只想使用从位图获取的普通简单的byte[]编码并发送到服务器。

有什么指针吗?

3个回答

138
你可以使用 copyPixelsToBuffer() 将像素数据移动到 Buffer,或者你可以使用 getPixels(),然后通过位移将整数转换为字节。 copyPixelsToBuffer() 可能是你想要使用的方法,以下是一个可以参考的示例:
//b is the Bitmap

//calculate how many bytes our image consists of.
int bytes = b.getByteCount();
//or we can calculate bytes this way. Use a different value than 4 if you don't use 32bit images.
//int bytes = b.getWidth()*b.getHeight()*4; 

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

byte[] array = buffer.array(); //Get the underlying array containing the data.

1
byte[] b; ByteBuffer byteBuffer = ByteBuffer.allocate(bitmapPicture.getByteCount()); bitmapPicture.copyPixelsToBuffer(byteBuffer); b = byteBuffer.array(); - Asad Khan
5
要调用getByteCount()方法,您需要使用API 12及以上的版本。 - Alfredo Cavalcanti
8
如果您查看getByteCount()的实现,它只是getRowBytes() * getHeight(),如果您针对< API 12,请自己计算一下。 - Anthony Chuinard
这个不起作用,最好使用bitmap.compress(...)获取字节数组。 - Demigod
1
@iDemigod,原帖明确表示不想使用Bitmap.Compress()。 - Jave
显示剩余4条评论

9

在@jave的答案中,以下行应该替换为:

int bytes = b.getByteCount();

请使用以下代码行和函数:

int bytes = byteSizeOf(b);

protected int byteSizeOf(Bitmap data) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1) {
    return data.getRowBytes() * data.getHeight();
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
    return data.getByteCount();
} else {
      return data.getAllocationByteCount();
}

6
BitmapCompat.getAllocationByteCount(bitmap);

找到所需的ByteBuffer大小是有帮助的


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