標籤:des android style blog color io ar strong div
1 /** 2 * 擷取壓縮後的圖片 (官網大圖片載入對應代碼) 3 * 4 * @param res 5 * @param resId 6 * @param reqWidth 7 * 所需圖片壓縮尺寸最小寬度 8 * @param reqHeight 9 * 所需圖片壓縮尺寸最小高度10 * @return11 */12 public static Bitmap decodeSampledBitmapFromResource(Resources res,13 int resId, int reqWidth, int reqHeight) {14 15 // 首先不載入圖片,僅擷取圖片尺寸16 final BitmapFactory.Options options = new BitmapFactory.Options();17 // 當inJustDecodeBounds設為true時,不會載入圖片僅擷取圖片尺寸資訊18 options.inJustDecodeBounds = true;19 // 此時僅會將圖片資訊會儲存至options對象內,decode方法不會返回bitmap對象20 BitmapFactory.decodeResource(res, resId, options);21 22 // 計算壓縮比例,如inSampleSize=4時,圖片會壓縮成原圖的1/423 options.inSampleSize = calculateInSampleSize(options, reqWidth,24 reqHeight);25 26 // 當inJustDecodeBounds設為false時,BitmapFactory.decode...就會返回圖片對象了27 options.inJustDecodeBounds = false;28 // 利用計算的比例值擷取壓縮後的圖片對象29 return BitmapFactory.decodeResource(res, resId, options);30 }31 32 /**33 * 計算壓縮比例值 (官網大圖片載入對應代碼) 34 * 35 * @param options36 * 解析圖片的配置資訊37 * @param reqWidth38 * 所需圖片壓縮尺寸最小寬度39 * @param reqHeight40 * 所需圖片壓縮尺寸最小高度41 * @return42 */43 public static int calculateInSampleSize(BitmapFactory.Options options,44 int reqWidth, int reqHeight) {45 // 儲存圖片原寬高值46 final int height = options.outHeight;47 final int width = options.outWidth;48 // 初始化壓縮比例為149 int inSampleSize = 1;50 51 // 當圖片寬高值任何一個大於所需壓縮圖片寬高值時,進入迴圈計算系統52 if (height > reqHeight || width > reqWidth) {53 54 final int halfHeight = height / 2;55 final int halfWidth = width / 2;56 57 // 壓縮比例值每次迴圈兩倍增加,58 // 直到原圖寬高值的一半除以壓縮值後都~大於所需寬高值為止59 while ((halfHeight / inSampleSize) >= reqHeight60 && (halfWidth / inSampleSize) >= reqWidth) {61 inSampleSize *= 2;62 }63 }64 return inSampleSize;65 }
android 官網處理圖片 代碼