首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 從 assets 載入圖片並顯示於 ImageView:正確使用 InputStream 與 BitmapFactory

     編輯:程式設計綜合問答

錯誤做法

嘗試用 file:///android:asset/ 當作 Uri,或 Uri.parse("file:///android_asset/..."),均無法被 ImageView.setImageURI 解析。

正確做法

public void loadImageFromAssets(String fileName, ImageView imageView) {
    try (InputStream is = getAssets().open(fileName)) {
        Bitmap bitmap = BitmapFactory.decodeStream(is);
        imageView.setImageBitmap(bitmap);
    } catch (IOException e) {
        e.printStackTrace();
        // 設定預設圖或錯誤佔位圖
        imageView.setImageResource(R.drawable.ic_error);
    }
}

大圖優化:inSampleSize 避免 OOM

public Bitmap decodeSampledBitmapFromAssets(String fileName, int reqWidth, int reqHeight) {
    // 第一次解碼只讀邊界
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    try (InputStream is = getAssets().open(fileName)) {
        BitmapFactory.decodeStream(is, null, options);
    } catch (IOException e) { return null; }

    // 計算縮放比
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;

    try (InputStream is = getAssets().open(fileName)) {
        return BitmapFactory.decodeStream(is, null, options);
    } catch (IOException e) { return null; }
}

private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    int inSampleSize = 1;
    if (options.outHeight > reqHeight || options.outWidth > reqWidth) {
        int halfH = options.outHeight / 2;
        int halfW = options.outWidth / 2;
        while ((halfH / inSampleSize) >= reqHeight && (halfW / inSampleSize) >= reqWidth) {
            inSampleSize *= 2;
        }
    }
    return inSampleSize;
}

注意事項

  • assets 目錄下的檔案**不可建立子目錄層級過深**(建議扁平化),且檔名**區分大小寫**。
  • 若圖片極多或需頻繁更新,建議改用網路下載 + 快取(Glide/Picasso/Coil)。
  • assets 檔案打包在 APK 內,安裝後不可修改;需可寫入請首次複製到 getFilesDir()。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved