将位图转换为byteArray android

Asa*_*han 48 base64 android bytearray bitmap

我有一个位图,我想通过编码到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);
Run Code Online (Sandbox Code Playgroud)

现在我只是不想使用任何压缩,也不想从位图中使用任何格式简单的byte [],我可以编码并发送到服务器.

有什么指针吗?

Jav*_*ave 133

您可以使用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.
Run Code Online (Sandbox Code Playgroud)

  • 如果你看一下getByteCount()impl它只是getRowBytes()*getHeight(),如果你的目标是<API 12,那么自己做一个数学运算. (7认同)
  • @ShailAdi调用getByteCount()你将获得API级别12. (5认同)

Naj*_*hah 7

而不是@jave中的以下行回答:

int bytes = b.getByteCount();
Run Code Online (Sandbox Code Playgroud)

使用以下行和功能:

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();
}
Run Code Online (Sandbox Code Playgroud)


小智 5

BitmapCompat.getAllocationByteCount(bitmap);
Run Code Online (Sandbox Code Playgroud)

有助于找到所需的 ByteBuffer 大小