将位图转换为 byteArray android [英] Converting bitmap to byteArray android
问题描述
我有一个位图,我想通过将其编码为 base64 将其发送到服务器,但我不想将图像压缩为 png 或 jpeg.
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.
现在我之前做的是.
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.
有什么指点吗?
推荐答案
您可以使用 copyPixelsToBuffer()
将像素数据移动到 Buffer
,或者你可以使用 getPixels()
然后通过位移将整数转换为字节.
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()
可能是你想要使用的,所以这里是一个关于如何使用它的例子:
copyPixelsToBuffer()
is probably what you'll want to use, so here is an example on how you can use it:
//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.
这篇关于将位图转换为 byteArray android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!