将位图转换为 byteArray android
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10191871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting bitmap to byteArray android
提问by Asad Khan
I have a bitmap that I want to send to the server by encoding it to base64 but I do not want to compress the image in either png or jpeg.
我有一个位图,我想通过将其编码为 base64 将其发送到服务器,但我不想以 png 或 jpeg 格式压缩图像。
Now what I was previously doing was.
现在我之前在做的是。
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);
Now I just dont want to use any compression nor any format plain simple byte[] from bitmap that I can encode and send to the server.
现在我只是不想使用任何压缩或任何格式简单的字节 [] 来自我可以编码并发送到服务器的位图。
Any pointers?
任何指针?
回答by Jave
You can use copyPixelsToBuffer()
to move the pixel data to a Buffer
, or you can use getPixels()
and then convert the integers to bytes with bit-shifting.
您可以使用copyPixelsToBuffer()
将像素数据移动到 a Buffer
,或者您可以使用getPixels()
然后将整数转换为带有位移位的字节。
copyPixelsToBuffer()
is probably what you'll want to use, so here is an example on how you can use it:
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.
回答by Najeebullah Shah
instead of the following line in @jave answer:
而不是@jave 答案中的以下行:
int bytes = b.getByteCount();
Use the following line and function:
使用以下行和函数:
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();
}
回答by Jobin Jacob Kavalam
BitmapCompat.getAllocationByteCount(bitmap);
is helpful to find the required size of the ByteBuffer
有助于找到所需的 ByteBuffer 大小