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

Android 圖片路徑 String 賦值給 ImageView:本地文件 vs 網絡圖片完整方案

     編輯:程式設計綜合問答

場景區分

來源類型路徑示例處理方式
本地文件/storage/emulated/0/Pictures/photo.jpg
file:///data/user/0/pkg/cache/img.png
BitmapFactory.decodeFile / Glide.load(File)
Content URIcontent://media/external/images/media/123ContentResolver.openInputStream + decodeStream / Glide.load(Uri)
Assets 內部file:///android_asset/logo.pngAssetManager.open + decodeStream
網絡 URLhttps://example.com/avatar.png必須用網絡請求庫(Glide/Picasso/Coil)
Base64/Data URIdata: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);
    }
}

關鍵優化:inSampleSize 防止 OOM

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()(舊版本)或依賴庫自動管理內存池。
  • 列表項複用時未取消舊請求,導致圖片錯位,Glide 自動處理此問題。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved