bitmap位图是Drawable的一种,Drawable是Android处理图像通用的类
Bitmap的格式有jpg,png等常见图片格式
Bitmap如何加载:
BitmapFactory提供了四种方法:
decodeFile,decodeResource,decodeStream,decodeByteArray,前两种也是间接调用了decodeStream方法
Bitmap高效加载:
采用BitmapFactory.Options来加载所需尺寸,设置inSampleSize采样率(官方建议为2的倍数)
步骤:
1.BitmapFactory.Options的inJustDecodeBounds方法设为true,加载图片宽高信息
2.取出宽高信息,outWidth,outHeight
3.根据图片宽高和所需宽高计算出采样率
4.BitmapFactory.Options的inJustDecodeBounds方法设为false,并且加载图片
(inJustDecodeBounds方法为true时,只解析图片宽高信息,不会加载图片)
//根据resourceID获取Bitmap,第三第四个参数为需要的宽高
public Bitmap getScalingBitmapFromResource(Resources resources,int resId,int reqWidth,int reqHeight){
BitmapFactory.Options options=new BitmapFactory.Options();
//加载图片宽高
options.inJustDecodeBounds=true;
BitmapFactory.decodeResource(resources,resId,options);
//计算得出采样率
options.inSampleSize=calculateInSampleSize(options,reqWidth,reqHeight);
//根据采样率高效的加载图片
options.inJustDecodeBounds=false;
return BitmapFactory.decodeResource(resources,resId,options);
}
//根据需要的宽高和图片本身的宽高,计算得出图片采样率
public int calculateInSampleSize(BitmapFactory.Options options,int reqWidth,int reqHeight){
int height=options.outHeight;
int width=options.outWidth;
int inSampleSize=1;
if (height>reqHeight&&width>reqWidth){
int halfHeight=height/2;
int halfWidth=width/2;
while ((halfHeight/inSampleSize)>=reqHeight&&(halfWidth/inSampleSize)>=reqWidth){
inSampleSize=inSampleSize*2;
}
}
return inSampleSize;
}
(FileInputStream是有序文件流,两次decodeStream影响了文件流的位置属性导致第二次decodeStream时得到null,为了解决这个问题可以fileInputStream.getFD()获取文件描述符,再BitmapFactory.decodeFileDescriptor()方法加载缩放后的Bitmap)
Bitmap大小计算
bitmap.getRowBytes() * bitmap.getHeight();
在API12提供了getByteCount()方法,实现方法也是上面的那种
通常加载图片还会用到缓存机制来避免频繁网络请求和提高速度,缓存机制请看我的这篇博客
https://blog.csdn.net/yh18668197127/article/details/86705688
一个完整的网络请求+二级缓存的Bitmap图片加载轮子(自己写的只实现了基本功能,非常粗糙)