java 如何以 KB 为单位获取保存在字节数组中的图像的大小

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

How to get size of an image that is held in a byte array in KB

javaandroid

提问by Chandra Sekhar

I want to find out the size of an image that is held in a byte array in KB

我想找出以 KB 为单位的字节数组中保存的图像的大小

Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.mPicture);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object   
byte[] b = baos.toByteArray();

The following logs display two different results for an image that is 11.7KB:

以下日志显示11.7KB图像的两种不同结果:

Log.d(TAG, "bm size: " + bm.getByteCount()/1024); // 942
Log.d(TAG, "baos size: " + baos.size()/1024); // 81
Log.d(TAG, "byte size: " + b.length/1024); // 81

Which is the correct result or how do I get the correct result?? Any help is appreciated.

哪个是正确的结果或者我如何得到正确的结果?任何帮助表示赞赏。

回答by Chandra Sekhar

bm.getByteCount()/1024 // 942is the original size of your image

bm.getByteCount()/1024 // 942是图像的原始尺寸

baos.size()/1024 // 81is the size after the image has been compressed

baos.size()/1024 // 81是图片压缩后的大小

The first gives the size of bitmap which represents the original image resourcebut the next two give the size of the stream or the byte array representing the compressedone. So the first one returns a bigger value than the next two.

第一个给出表示原始图像资源的位图的大小,但接下来的两个给出流的大小或表示压缩的字节数组。所以第一个返回比接下来两个更大的值。