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 }