要在 ImageView 中顯示外部儲存空間的圖片,先在版面檔裡放好容器:
<ImageView
Android:id="@+id/imgView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
接著在 Activity 中透過 BitmapFactory.decodeFile() 解碼,再交給 ImageView 顯示:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button)findViewById(R.id.btn_b);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ImageView view = (ImageView)findViewById(R.id.imgView);
String img = "/mnt/extsd/11.png";
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Log.i("chen", "============options=======" + options);
Bitmap bm = BitmapFactory.decodeFile(img, options);
view.setImageBitmap(bm);
}
});
}
這段程式有兩個實務上必須留意的細節。
第一是 inSampleSize = 2。解碼前先設定取樣率,會讓 BitmapFactory 只保留原圖的四分之一像素量,大幅降低記憶體佔用;直接解碼大尺寸照片在舊型裝置上很容易觸發 OutOfMemoryError,因此這個參數幾乎是必備的。
第二是路徑與權限。/mnt/extsd/ 是部分外接 SD 卡的掛載點,各家廠商與 Android 版本差異很大,硬編碼路徑容易失效;較穩妥的做法是透過 Environment.getExternalStorageDirectory() 取得路徑,並在清單中宣告 READ_EXTERNAL_STORAGE(Android 6.0 以上還需執行期動態請求權限)。若目標是 API 29 以後的版本,則應改用 MediaStore 或儲存空間存取架構(SAF)來讀取外部檔案。
更多 Android 相關資訊見 Android 專題頁面 https://www.linuxidc.com/topicnews.aspx?tid=11