简体   繁体   English

Android:从Uri压缩位图

[英]Android: Compress Bitmap from Uri

Take a picture with the normal smartphone camera. 使用普通的智能手机相机拍照。

Ok I've been Googling this for a while now, and everyone seems to use something like the following: 好的,我已经谷歌搜索了一段时间了,所有人似乎都使用如下内容:

Bitmap bm = BitmapFactory.decodeStream(getContentResolver().openInputStream(fileUri));
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 25, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

I use this to check the file size: 我用它来检查文件大小:

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
protected int sizeOf(Bitmap data) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1) {
        return data.getRowBytes() * data.getHeight();
    } else {
        return data.getByteCount();
    }
}

The Bitmap is not getting any smaller, before and after: 之前和之后Bitmap没有变小:

Log.d("image", sizeOf(bm)+"");
Log.d("image", sizeOf(decoded)+"");

Results: 结果:

11-05 02:51:52.739: D/image(2558): 20155392
11-05 02:51:52.739: D/image(2558): 20155392

Pointers? 指针?

Answer: 回答:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 50;
Bitmap bmpSample = BitmapFactory.decodeFile(fileUri.getPath(), options);

Log.d("image", sizeOf(bmpPic)+"");

ByteArrayOutputStream out = new ByteArrayOutputStream();                
bmSample.compress(Bitmap.CompressFormat.JPEG, 1, out);
byte[] byteArray = out.toByteArray();

Log.d("image", byteArray.length/1024+"");

The compress method, as mentioned in the documentation: compress方法,如文档中所述:

Write a compressed version of the bitmap to the specified outputstream. 将位图的压缩版本写入指定的输出流。 The bitmap can be reconstructed by passing a corresponding inputstream to BitmapFactory.decodeStream() 可以通过将相应的输入流传递给BitmapFactory.decodeStream()来重建位图

Thus the variable out now contains the compressed bitmap. 因此,变量out现在包含压缩的位图。 Since you check the size after calling decodeStream the bitmap is decompressed and returned to you. 由于在调用decodeStream后检查大小,因此位图会被解压缩并返回给您。 Therefore the size is same. 因此大小相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM