ImageView加載本地大圖片,易出現OOM內存不足現象,需要進行壓縮然后顯示。
1 /** 2 * 加載本地大圖片 3 * 4 * @param localPath 5 * @param context 6 * @return 7 */ 8 public static Bitmap decodeBitmap(String localPath, Context context) { 9 BitmapFactory.Options opts = new BitmapFactory.Options(); 10 // 置為true,僅僅返回圖片的分辨率 11 opts.inJustDecodeBounds = true; 12 BitmapFactory.decodeFile(localPath, opts); 13 // 得到原圖的分辨率; 14 int srcHeight = opts.outHeight; 15 int srcWidth = opts.outWidth; 16 // 得到設備的分辨率 17 int screenHeight = ScreenUtil.getScreenHeight(context); 18 int screenWidth = ScreenUtil.getScreenWidth(context); 19 // 通過比較得到合適的比例值; 20 // 屏幕的 寬320 高 480 ,圖片的寬3000 ,高是2262 3000/320=9 2262/480=5,,使用大的比例值 21 int scale = 1; 22 int sx = srcWidth / screenWidth; 23 int sy = srcHeight / screenHeight; 24 if (sx >= sy && sx > 1) { 25 scale = sx; 26 } 27 if (sy >= sx && sy > 1) { 28 scale = sy; 29 } 30 // 根據比例值,縮放圖片,並加載到內存中; 31 // 置為false,讓BitmapFactory.decodeFile()返回一個圖片對象 32 opts.inJustDecodeBounds = false; 33 // 可以把圖片縮放為原圖的1/scale * 1/scale 34 opts.inSampleSize = scale; 35 // 得到縮放后的bitmap 36 // Bitmap bm = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/lp.jpg", opts); 37 Bitmap bm = BitmapFactory.decodeFile(localPath, opts); 38 return bm; 39 }