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>