Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 按路徑讀取並顯示 SD 卡圖片的源碼示例

編輯:關於 Android 程式設計

需求很單純:已知 SD 卡上一張圖片的完整路徑,把它讀出來顯示在 ImageView 上。核心只有兩個 API——File.exists() 做前置檢查、BitmapFactory.decodeFile() 解碼。

package com.guo;

import java.io.File;

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

public class MainAct extends Activity {

    private ImageView img;

    // SD 卡上的圖片路徑
    private String filepath = "/sdcard/hot.png";

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

        img = (ImageView) findViewById(R.id.img);

        File file = new File(filepath);
        if (file.exists()) {
            Bitmap bm = BitmapFactory.decodeFile(filepath);
            // 將圖片顯示到 ImageView
            img.setImageBitmap(bm);
        }
    }
}

版面檔 main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/img"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>

權限宣告

讀取外部儲存空間必須在 AndroidManifest.xml 中聲明權限,否則 file.exists() 會回傳 false,而且不會給你任何錯誤提示——這是最容易誤判的地方。

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Android 4.4(API 19)之前只需要 WRITE_EXTERNAL_STORAGE 就能讀寫;4.4 之後讀取要明確宣告 READ_EXTERNAL_STORAGE。到了 Android 6.0(API 23)以上,這還會變成執行期動態權限,必須主動向使用者請求。

這個範例在真實專案中的問題

程式碼很短,但直接搬到正式專案會遇到幾個問題:

1. 路徑寫死,且過時

/sdcard/hot.png 這種寫法在早期機型可行,但從 Android 4.4 開始,/sdcard 只是個指向實際掛載點的軟連結,多使用者環境下更是每個使用者一個獨立目錄。正確做法是用系統 API 取得:

// 取得外部儲存空間的根目錄
File dir = Environment.getExternalStorageDirectory();

// 更好的做法:取得 App 專屬的外部目錄,不需要任何權限
File appDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);

getExternalFilesDir() 回傳的目錄在 App 解除安裝時會自動清除,而且不需要宣告任何儲存空間權限,是放置 App 自己產生的檔案的首選。若要讀取使用者的相簿,則應走 MediaStore。

2. 在主 thread 解碼大圖會 ANR

BitmapFactory.decodeFile() 是同步的 I/O 加解碼操作。一張 1200 萬畫素的照片解成 ARGB_8888 的 Bitmap 需要約 48MB 記憶體,在主 thread 執行幾乎必定觸發 ANR 或 OutOfMemoryError。

實務上必須做兩件事:放到背景 thread,並在解碼前先取樣縮小。

3. 沒有錯誤處理

decodeFile() 失敗時回傳 null 而不拋例外,接著 setImageBitmap(null) 不會報錯但畫面空白,很難查。應該判空並提供替代圖。

改良版本

public class ImageLoaderTask extends AsyncTask<String, Void, Bitmap> {

    private final ImageView target;
    private final int reqWidth;
    private final int reqHeight;

    public ImageLoaderTask(ImageView view, int width, int height) {
        this.target = view;
        this.reqWidth = width;
        this.reqHeight = height;
    }

    @Override
    protected Bitmap doInBackground(String... paths) {
        try {
            // 第一趟:只讀取尺寸,不真正解碼
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(paths[0], opts);

            // 依目標尺寸計算取樣率
            opts.inSampleSize = calculateInSampleSize(opts, reqWidth, reqHeight);
            opts.inJustDecodeBounds = false;

            return BitmapFactory.decodeFile(paths[0], opts);
        } catch (OutOfMemoryError e) {
            return null;
        }
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (bitmap != null) {
            target.setImageBitmap(bitmap);
        } else {
            target.setImageResource(R.drawable.default_placeholder);
        }
    }

    /**
     * 計算合適的取樣率。inSampleSize 只能是整數,
     * 取 2 的次方對多數解碼器來說效能最佳。
     */
    private static int calculateInSampleSize(BitmapFactory.Options opts,
                                             int reqWidth, int reqHeight) {
        final int height = opts.outHeight;
        final int width = opts.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }
}

// 使用方式
ImageView img = findViewById(R.id.img);
int size = getResources().getDimensionPixelSize(R.dimen.thumb_size);
new ImageLoaderTask(img, size, size).execute("/sdcard/hot.png");

這個版本解決了原範例的三個問題:inJustDecodeBounds = true 讓第一趟只讀取檔案頭取得尺寸而不配置像素記憶體,據此算出取樣率後第二趟才真正解碼;解碼在背景 thread 進行;並對 null 與 OutOfMemoryError 都做了處理。

最後補充一點:如果你只是想顯示 SD 卡上的圖片,而它其實是由相機或相簿產生的,那更合適的做法是查詢 MediaStore.Images.Media,用 ContentResolver 拿到 URI,再搭配 Glide 或 Coil 這類成熟的圖片載入庫。它們已經把快取、取樣、生命週期綁定、請求取消都處理好了,除非有特殊需求,否則沒必要自己實作。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved