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

Android 讀取圖片資源的三種途徑:drawable、assets 與 SD 卡

編輯:關於 Android 程式設計

專案裡取圖片的地方大致分三類:打包進 APK 的 drawable、放在 assets 的原始檔,以及外部儲存空間的 SD 卡。三者的 API 完全不同,這裡整理成對照表。

方式一:圖片放在 drawable 目錄

這是最常見的做法,用資源 ID 直接換成 Drawable 或 Bitmap。

(1)用 ID 取 Drawable

Drawable drawable = getResources().getDrawable(R.drawable.xxx);

(2)用 ID 取 Bitmap

Resources res = getResources();
Bitmap bitmap = BitmapFactory.decodeResource(res, id);

(3)只知道名稱時,先反查 ID

// name:圖片名稱;defType:資源類型(drawable、string 等);defPackage:專案包名
int id = res.getIdentifier(name, defType, defPackage);
Drawable drawable = getResources().getDrawable(id);

方式二:圖片放在 assets 目錄

assets 裡的檔案沒有資源 ID,得靠 AssetManager 開串流。

AssetManager asm = getAssets();
InputStream is = asm.open(name);   // name 為圖片檔名

// 取 Drawable
Drawable da = Drawable.createFromStream(is, null);

// 取 Bitmap
Bitmap bitmap = BitmapFactory.decodeStream(is);

方式三:圖片存在 SD 卡

先組出路徑,再交給 BitmapFactory。

String imgFilePath = Environment.getExternalStorageDirectory().toString()
        + "/DCIM/device.png";

(1)走 FileInputStream

FileInputStream fis = new FileInputStream(new File(imgFilePath));
Bitmap bmp = BitmapFactory.decodeStream(fis);

(2)直接用 decodeFile

ImageView iv = (ImageView) findViewById(R.id.image);
Bitmap bit = BitmapFactory.decodeFile("/sdcard/android.bmp");
iv.setImageBitmap(bit);

(3)用 createFromPath 取 Drawable

iv.setImageDrawable(Drawable.createFromPath(
        new File(Environment.getExternalStorageDirectory(), "camera.jpg")
                .getAbsolutePath()));

實務提醒:讀 SD 卡需要在清單檔宣告 READ_EXTERNAL_STORAGE(Android 6.0 起還要跑-time 權限),而 decode 大圖時記得搭配 BitmapFactory.Options.inSampleSize 做降採樣,否則 OOM 幾乎是必然。

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