2011年2月18日星期五

利用BitmapFactory.Options的inSampleSize對bitmap進行優化

在我的舊文章"從內部文件夾加載圖像視圖(ImageView)", "從SD Card加載圖像視圖(ImageView), 使用BitmapFactory"和"從網絡加載圖像視圖(ImageView)"中, 我展示了如何顯示位圖(bitmap), 但都是把位圖直接顯示在ImageView上. 這樣做有一個問題: 就是對系統資源很"大食", 特別是當源位圖是非常大時, 甚至可以使應用程序崩潰.

這篇文章以"從SD Card加載圖像視圖(ImageView)"為例, 首先檢查源位圖的大小, 通過BitmapFactory.Options設置inSampleSize, 這樣做可以減少對系統資源的要求.

利用BitmapFactory.Options的inSampleSize對bitmap進行優化

先把較大的圖片文件複製到SD Card中.

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<ImageView
android:id="@+id/imageview"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="center"
/>
</LinearLayout>


Java源代碼
package com.AndroidImage;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;

public class AndroidImage extends Activity {

private String imageFile = "/sdcard/AndroidSharedPreferencesEditor.png";
/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

ImageView myImageView = (ImageView)findViewById(R.id.imageview);
//Bitmap bitmap = BitmapFactory.decodeFile(imageFile);
//myImageView.setImageBitmap(bitmap);

Bitmap bitmap;
float imagew = 300;
float imageh = 300;

BitmapFactory.Options bitmapFactoryOptions = new BitmapFactory.Options();
bitmapFactoryOptions.inJustDecodeBounds = true;
bitmap = BitmapFactory.decodeFile(imageFile, bitmapFactoryOptions);

int yRatio = (int)Math.ceil(bitmapFactoryOptions.outHeight/imageh);
int xRatio = (int)Math.ceil(bitmapFactoryOptions.outWidth/imagew);

if (yRatio > 1 || xRatio > 1){
if (yRatio > xRatio) {
bitmapFactoryOptions.inSampleSize = yRatio;
Toast.makeText(this,
"yRatio = " + String.valueOf(yRatio),
Toast.LENGTH_LONG).show();
}
else {
bitmapFactoryOptions.inSampleSize = xRatio;
Toast.makeText(this,
"xRatio = " + String.valueOf(xRatio),
Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(this,
"inSampleSize = 1",
Toast.LENGTH_LONG).show();
}

bitmapFactoryOptions.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(imageFile, bitmapFactoryOptions);
myImageView.setImageBitmap(bitmap);
}

}

沒有留言:

發佈留言