| 來源類型 | 路徑示例 | 處理方式 |
|---|---|---|
| 本地文件 | /storage/emulated/0/Pictures/photo.jpg file:///data/user/0/pkg/cache/img.png | BitmapFactory.decodeFile / Glide.load(File) |
| Content URI | content://media/external/images/media/123 | ContentResolver.openInputStream + decodeStream / Glide.load(Uri) |
| Assets 內部 | file:///android_asset/logo.png | AssetManager.open + decodeStream |
| 網絡 URL | https://example.com/avatar.png | 必須用網絡請求庫(Glide/Picasso/Coil) |
| Base64/Data URI | data:image/png;base64,iVBORw0K... | Base64.decode + decodeByteArray |
// Gradle 依賴
implementation "com.github.bumptech.glide:glide:4.16.0"
kapt "com.github.bumptech.glide:compiler:4.16.0"
// 一行代碼處理所有類型
Glide.with(context)
.load(imagePathOrUrl) // String/Uri/File/Integer(resourceId)
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.into(imageView);
public static void loadLocalImage(Context context, String path, ImageView iv) {
try {
File file = new File(path);
if (!file.exists()) {
// 嘗試 Content URI
Uri uri = Uri.parse(path);
if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
try (InputStream is = context.getContentResolver().openInputStream(uri)) {
Bitmap bmp = BitmapFactory.decodeStream(is);
iv.setImageBitmap(bmp);
}
return;
}
}
// 普通文件路徑
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = calculateInSampleSize(opts, iv.getWidth(), iv.getHeight());
Bitmap bmp = BitmapFactory.decodeFile(path, opts);
iv.setImageBitmap(bmp);
} catch (Exception e) {
iv.setImageResource(R.drawable.error);
}
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
if (reqWidth == 0 || reqHeight == 0) return 1;
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;
}
BitmapFactory.decodeFile(networkUrl) 會拋異常,網絡路徑必須下載後再解碼。recycle()(舊版本)或依賴庫自動管理內存池。