嘗試用 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);
}
}
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 目錄下的檔案**不可建立子目錄層級過深**(建議扁平化),且檔名**區分大小寫**。assets 檔案打包在 APK 內,安裝後不可修改;需可寫入請首次複製到 getFilesDir()。