Android:从Uri压缩位图

3

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

好的,我已经谷歌搜索了一段时间,似乎每个人都使用类似以下的东西:

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

位图在缩放前后大小没有改变:

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

你把日志语句放在哪里? - Amulya Khare
在我调用 sizeOf(Bitmap data) 方法之后! - basickarl
你能把它贴成代码吗?我有一种感觉,你可能正在记录相同数据的大小.. 因此输出也是相同的。 - Amulya Khare
@AmulyaKhare 我也这么想,但我双重检查了一下,我知道输出在同一秒钟(很奇怪:S)。 - basickarl
看我的回答,解释了为什么输出是相同的。如果你想在屏幕上显示一个压缩版本,你应该使用 inSampleSize。阅读这个链接:https://dev59.com/22gu5IYBdhLWcg3w0aGg#11061315 - Amulya Khare
1个回答

1

如文档所述,compress方法:

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接