一、Bitmap
1、Bitmap组成
Bitmap的存储包含两个部分:像素以及长、宽、颜色等描述信息。像素是Bitmap最占内存的地方,长宽和像素位数是用来描述图片的,可以通过这些信息计算出图片的像素占用的内存的大小。
常用方法:
- getWidth()
- getHeight()
- Config getConfig() 枚举值
枚举类型 | 每个像素内存 |
ALPHA_8 | 1byte |
RGB_565 | 2byte |
ARGB_4444 | 2byte |
ARGB_8888(默认) | 4byte |
(1)图片占用内存的计算
假设一张图片1024*1024,模式为ARGB_8888的图片,那么它占有的内存就是1024*1024*4=4MB
2、Bitmap加载
Bitmap的加载离不开BitMapFactory类
- 加载文件 (间接调用decodeStream)
BitmapFactory.decodeFile(String pathName);
BitmapFactory.decodeFile(String pathName,Options opts)
- 加载id资源(间接调用decodeStream)
BitmapFactory.decodeResource(Resource res,int id,Options opts)
BitmapFactory.decodeResource(Resource res,int id)
- 加载输入流
BitmapFactory.decodeStream(InputStream is)
- 加载字节
BitmapFactory.decodeByteArray(myByte,0,myByte.length,options opts)
3、Options参数
(1)inSampleSize 采样率
inSampleSize的值必须大于1时才会有效果,且采样率同时作用于宽和高。他的取值应该总为2的整数倍,否则会向下取整,取一个最接近2的整数倍,比如inSampleSize=3,系统会取inSampleSize=2。
(2)inJustDecodeBounds
InJustDecodeBounds值为true时,执行decodeXXX方法时,BitmapFactory只会解析图片的原始宽高信息,并不会真正的加载图片。值为false时,才会真正的加载图片。
4、使用实例
/**
* 按比例缩放
* @param orinWidth 原始宽
* @param orinHeight 原始高
* @param nowWidth 目标宽
* @param nowHeight 目标高
* @return
*/
private int getSample(int orinWidth, int orinHeight, int nowWidth, int nowHeight) {
int sample = 1;
if (orinWidth > orinHeight && orinWidth > nowWidth) {
sample = orinWidth / nowWidth;
} else if (orinWidth < orinHeight && orinHeight > nowHeight) {
sample = orinHeight / nowHeight;
}
if (sample <= 0) {
sample = 1;
}
return sample;
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//并不会真正加载图片,加载的图片的数据
BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher, options);
int outWidth = options.outWidth;
int outHeight = options.outHeight;
options.inSampleSize = getSample(outWidth, outHeight, 300, 300);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher, options);
imageView.setImageBitmap(bitmap);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = tru
来源:CSDN
作者:影子听说
链接:https://blog.csdn.net/u011275346/article/details/103795018