位图大小远大于加载它的文件大小

时间:2014-10-27 10:04:57

标签: android

我正在使用以下代码从android中的图像文件中检索位图:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(path, options);

但是,位图的大小是文件大小的两倍多。例如,对于大小为520kb的文件,位图大小约为1.3MB。有没有办法可以获得与文件大小相同的位图?

2 个答案:

答案 0 :(得分:5)

位图大小是没有压缩的纯内存数据。您可以使用每个像素4个字节计算大小(使用您的设置)。

您的文件可能采用jpg等压缩格式。如果没有压缩,它将占用相同的空间。

位图在内存中保持未压缩的原因基本上就是性能。您可以以未压缩的方式更快地读取数据并使用它。例如,如果您想查看特定像素的颜色,则需要先解压缩数据。这需要花费时间,检查的像素越多,花费的时间就越多。

从存储中读取文件时,与完整阅读过程相比,解压缩只需要一段可忽略的时间。因此,与按需提供相比,您不会产生重大的性能影响。解压缩。

答案 1 :(得分:-1)

尝试这样可以帮到你,

public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
 try {
     //Decode image size
     BitmapFactory.Options o = new BitmapFactory.Options();
     o.inJustDecodeBounds = true;
     BitmapFactory.decodeStream(new FileInputStream(f),null,o);

     //The new size we want to scale to
     final int REQUIRED_WIDTH=WIDTH;
     final int REQUIRED_HIGHT=HIGHT;
     //Find the correct scale value. It should be the power of 2.
     int scale=1;
     while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
         scale*=2;

     //Decode with inSampleSize
     BitmapFactory.Options o2 = new BitmapFactory.Options();
     o2.inSampleSize=scale;
     return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
 } catch (FileNotFoundException e) {}
 return null;
}