【问题标题】:Android: Compress Bitmap from UriAndroid:从 Uri 压缩位图
【发布时间】:2013-11-15 20:15:49
【问题描述】:

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

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

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

【问题讨论】:

  • 你把你的日志语句放在哪里..?
  • 在我调用 sizeOf(Bitmap data) 之后直接!
  • 你能把它贴在代码里吗?我感觉您可能正在记录相同数据的大小..因此输出是相同的..
  • @AmulyaKhare 我也这么认为,不过我仔细检查了一遍,我知道输出是在同一秒(奇怪:S)。
  • 查看我的答案.. 解释为什么输出相同.. 如果您尝试在屏幕上显示压缩版本,您应该使用inSampleSize .. 阅读此stackoverflow.com/a/11061315/827110

标签: android


【解决方案1】:

compress 方法,如文档中所述:

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

因此变量out 现在包含压缩位图。由于您在调用decodeStream 后检查了大小,因此位图已解压缩 并返回给您。所以大小是一样的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 2019-05-04
    • 2015-04-23
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多