Android之Bitmap 高效加载

一张图片(BitMap)占用的内存=图片长度*图片宽度*单位像素占用的字节数

 图片格式(Bitmap.Config

 一张100*100的图片占用内存的大小

 ALPHA_8

 图片长度*图片宽度

 100*100=10000字节

 ARGB_4444

 图片长度*图片宽度*2

 100*100*2=20000字节

 ARGB_8888

 图片长度*图片宽度*4

 100*100*4=40000字节

 RGB_565 

 图片长度*图片宽度*2

 100*100*2=20000字节

 
 
减小图片内存的方式只有改变,图片的格式,缩减长宽,改变采样率:
 1 public static Bitmap getBitmapByPath(String path,int setWidth,int setHeight){
 2             //创建一个空的Bitmap
 3             Bitmap  bitmap = null;
 4             //获取Options对象
 5             BitmapFactory.Options options = new BitmapFactory.Options();
 6             //将inJustDecodeBounds属性设置为true,当inJustDecodeBounds属性为true的时候,BitmapFactory只会读取原始的宽高
 7             //并不会真正的加载图片
 8             options.inJustDecodeBounds = true;
 9             //因为上边已经把inJustDecodeBounds属性设置为了true,所以这里不会真正的加载图片,只会读取原始的宽高
10             BitmapFactory.decodeFile(path, options);
11             //获取图片的原始高
12             int height =options.outHeight;
13             //获取图片原始的宽
14             int width = options.outWidth;
15             //声明一个原始的采样率
16             int getinSampleSize = 1;
17             //如果原始宽高大于目标宽高
18             if(height>setHeight || width>setWidth){
19                 //取原始宽高的2/1
20                 int halfHeight = height/2;
21                 int halfWidth = width/2;
22                 //根据条件来计算采样率
23                 while ((halfHeight / getinSampleSize) >= setHeight && (halfWidth / getinSampleSize) >= setWidth) {
24                     getinSampleSize *=2;
25                 }
26             }
27             //将计算出来的采样率付给options.inSampleSize,使用使用计算出来的采样率
28             options.inSampleSize = getinSampleSize;
29             //将inJustDecodeBounds属性设置为false
30             options.inJustDecodeBounds = false;
31             //因为上边已经将inJustDecodeBounds属性设置为false,这里将真正的加载图片
32             bitmap = BitmapFactory.decodeFile(path,options);
33             return bitmap;
34         }
原文地址:https://www.cnblogs.com/shiguotao-com/p/5170253.html