Bitmap的效果虽然很好,即有色彩RGB又有透明度Alqha,但同时意味着图片将会占据更大的内存空间,手机的内存毕竟是有限的,如果加载大量的Bitmap图片,很有可能会出现内存溢出的现象。为了防止内存溢出,应该引入bitmap图片的二次采样生成缩略图,这样可以大大优化内存,这也是我们Android开发者十分在意的。
下面是实现Bitmap图片的二次采样的详细代码:
public class MainActivity extends AppCompatActivity {
private Button mButton;
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
//初始化控件
mButton = (Button) findViewById(R.id.btn_show);
mImageView = (ImageView) findViewById(R.id.iv_show);
//点击按钮,对本地的一张位图进行二次采样
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Bitmap bitmap = decodeBitmapFromResource(getResources(), R.mipmap.sd, 500, 450);
mImageView.setImageBitmap(bitmap);
}
});
}
/**
* 计算采样比例
* @param options
* @param reqWidth 希望加载位图的宽度
* @param reqHeight
* @return 返回采样比例
*/
public int calcInSampleSize(BitmapFactory.Options options,int reqWidth,int reqHeight){
//获取位图原本的宽和高
int w = options.outWidth;
int h = options.outHeight;
int inSampleSize = 1; //初始化采样比例为1
if (w > reqWidth || h > reqHeight){ //原图的宽或高大于预期位图的宽或高
if (w > h){ //原图的宽大于高,采样比例的计算公式:根据小的计算,实际的 / 预期的
inSampleSize = Math.round((float) h / (float) reqHeight);
}else if (h > w){
inSampleSize = Math.round((float) w / (float) reqWidth);
}
}
return inSampleSize; //最后把计算的采样比例返回回去
}
/**
* 根据采样比例重新采样位图
* @param res
* @param resId 资源id,也可以加载网络图片
* @param reqWidth
* @param reqHeight
* @return
*/
public Bitmap decodeBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight){
BitmapFactory.Options options = new BitmapFactory.Options();
//1,设置options.inJustDecodeBounds为true,此时只计算图片的宽高等属性,而不真正的加载图片的内容
options.inJustDecodeBounds = true;
//2,解析位图,把options传进去,其实此时只能获取位图的宽高等属性
BitmapFactory.decodeResource(res, resId, options);
//3,设置位图的采样比例
options.inSampleSize = calcInSampleSize(options,reqWidth,reqHeight);
//4,设置inJustDecodeBounds为false
options.inJustDecodeBounds = false;
//5,真正解析位图
Bitmap bitmap = BitmapFactory.decodeResource(res, resId, options);
//6,把解析的位图返回回去
return bitmap;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.administrator.bitmap.MainActivity">
<Button
android:id="@+id/btn_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="加载位图" />
<ImageView
android:id="@+id/iv_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/e"/>
</LinearLayout>