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);

现在我只是不想使用任何压缩,也不想使用任何格式的简单字节 [] 来自我可以编码并发送到服务器的位图。

任何指针?

4

3 回答 3

135

您可以使用copyPixelsToBuffer()将像素数据移动到 a 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.
于 2012-04-17T13:21:00.243 回答
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();
}
于 2015-04-23T06:27:37.157 回答
6
BitmapCompat.getAllocationByteCount(bitmap);

有助于找到所需的 ByteBuffer 大小

于 2017-04-21T16:11:55.530 回答