We all know,編寫的應用程序都是有一定內存限制的,程序佔用了過高的內存就容易出現OOM(OutOfMemory)異常。因此在展示高分辨率圖片的時候,最好先將圖片進行壓縮,壓縮後的圖片大小應該和用來展示它的控件大小相近,這樣可以協調顯示效果和內存佔用。
BitmapFactory.Options這個類,有一個字段叫做 inJustDecodeBounds 。SDK中對這個成員的說明是這樣的: If set to true, the decoder will return null (no bitmap), but the out… 也就是說,如果我們把它設爲true,那麼BitmapFactory.decodeFile(String path, Options opt)並不會真的返回一個Bitmap給你,它僅僅會把它的寬,高取回來給你,這樣就不會佔用太多的內存,也就不會那麼頻繁的發生OOM了。
下面通過具體實例來展示怎麼實現縮略圖。
1.佈局文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/mei" />
<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_below="@+id/imageView1"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:src="@drawable/mei" />
</RelativeLayout>
2.MainActivity.java代碼如下:
package org.yayun.demo;
//省略導入包
public class MainActivity extends Activity {
private ImageView imageView1;
private ImageView imageView2;
Bitmap mBitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
}
private void initView(){
imageView1=(ImageView)findViewById(R.id.imageView1);
imageView2=(ImageView)findViewById(R.id.imageView2);
//讀取資源圖片
mBitmap=readBitMap();
//對資源圖片進行縮放
imageView2.setImageBitmap(zoomBitmap(mBitmap, mBitmap.getWidth()/4, mBitmap.getHeight()/4));
}
/**
* 讀取資源圖片
* @return
*/
private Bitmap readBitMap(){
BitmapFactory.Options opt=new BitmapFactory.Options();
/*
* 設置讓解碼器以最佳方式解碼
*/
opt.inPreferredConfig=Bitmap.Config.RGB_565;
//下面兩個字段需要組合使用
opt.inPurgeable=true;
opt.inInputShareable=true;
/*
* 獲取資源圖片
*/
InputStream is=this.getResources().openRawResource(R.drawable.mei);
return BitmapFactory.decodeStream(is, null, opt);
}
/**
* 縮放圖片
* @param bitmap
* @param w
* @param h
* @return
*/
public Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidht = ((float) w / width);
float scaleHeight = ((float) h / height);
/*
* 通過Matrix類的postScale方法進行縮放
*/
matrix.postScale(scaleWidht, scaleHeight);
Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
return newbmp;
}
}
定義了兩個ImageView,第一個ImageView不進行任何操作,直接顯示圖片,第二個圖片進行了壓縮顯示。上面代碼中主要包含了兩個方法,readBitMap和zoomBitmap方法。readBitMap先通過流的方式將資源文件讀入,然後調用了BitmapFactory的decodeStream方法將流轉換成Bitmap對象返回。zoomBitmap是實現圖片縮放的方法,需要三個參數,bitmap,w 和h,bitmap就是前一個方法獲取的對象,w和h是壓縮比。這裏將原圖片的寬高壓縮至原來的1/4。調用Matrix類的postScale方法進行了圖片的壓縮,最後將壓縮後的bitmap對象返回,設置在imageview中,工作就結束了。
3.運行實例: