2013-11-05 71 views
3

使用普通的智能手机相机拍摄照片。Android:从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(); 
    } 
} 

的位图是没有得到任何较小,前后:

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

你把你的日志语句放在哪里..? –

+0

直接调用sizeOf(位图数据)后! –

+0

你可以在代码中发布它吗?我有这样的感觉,你可能会记录相同的数据大小..因此输出是相同的。 –

回答

0

compress方法中,作为文档中提到:

写位图的压缩版本到指定的输出流。位图可通过使相应的InputStream进行重建,以BitmapFactory.decodeStream()

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

+0

正确的道理! –