java 将字节数组解码为Java压缩过的位图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5243547/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:10:41  来源:igfitidea点击:

Decode byte array to bitmap that has been compressed in Java

javaandroidbitmapcompressionbytearray

提问by cutts

I am compressing a bitmap in the following way

我正在按以下方式压缩位图

Bitmap bmpSig = getMyBitMap();
int size = bmpSig.getWidth() * bmpSig.getHeight();
ByteArrayOutputStream out = new ByteArrayOutputStream(size);
bmpSig.compress(Bitmap.CompressFormat.JPEG, 100, out);   
byte[] bytSig = out.toByteArray();

I am then trying to display the image in an Android ImageView from the byte array. When I do this I get an image that is completely black image.

然后我试图从字节数组中在 Android ImageView 中显示图像。当我这样做时,我得到一个完全黑色的图像。

ImageView myImg = (ImageView) findViewById(R.id.img_view);
myImg.setImageBitmap(BitmapFactory.decodeByteArray(bytSig, 0, bytSig.length));

I'm assuming it's because I am missing a step before BitmapFactory.decodeByteArray() to reverse the jpeg compression. Or have I misunderstood how the compression works?

我假设这是因为我在 BitmapFactory.decodeByteArray() 之前缺少一个步骤来反转 jpeg 压缩。还是我误解了压缩的工作原理?

采纳答案by cutts

I didn't realise that the background of my bitmap (from a Canvas object) was transparent. Since this bitmap is just black lines on a white background the black image is due to compressing to JPEG giving the image a black background.

我没有意识到位图的背景(来自 Canvas 对象)是透明的。由于此位图只是白色背景上的黑色线条,因此黑色图像是由于压缩为 JPEG 使图像具有黑色背景。

I have changed

我改变了

bmpSig.compress(Bitmap.CompressFormat.JPEG, 100, out); 

to

bmpSig.compress(Bitmap.CompressFormat.PNG, 100, out); 

And it is working as expected.

它按预期工作。