繁体   English   中英

Android:从Uri压缩位图

[英]Android: Compress Bitmap from Uri

使用普通的智能手机相机拍照。

好的,我已经谷歌搜索了一段时间了,所有人似乎都使用如下内容:

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()));

我用它来检查文件大小:

@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();
    }
}

之前和之后Bitmap没有变小:

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

结果:

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

指针?

回答:

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+"");

compress方法,如文档中所述:

将位图的压缩版本写入指定的输出流。 可以通过将相应的输入流传递给BitmapFactory.decodeStream()来重建位图

因此,变量out现在包含压缩的位图。 由于在调用decodeStream后检查大小,因此位图会被解压缩并返回给您。 因此大小相同。

暂无
暂无

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

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