安卓圖片壓縮處理的終極方法,適用於各種機型
阿新 • • 發佈:2018-11-01
//直接呼叫getimage,引數為:路徑、寬、高 public static Bitmap getimage(String pathName, int reqWidth, int reqHeight) { final BitmapFactory.Options options = new BitmapFactory.Options(); // 若要對圖片進行壓縮,必須先設定Option的inJustDecodeBounds為true才能進行Option的修改 options.inJustDecodeBounds = true; // 第一次decodeFile是獲取到options.outHeight和options.outWidth BitmapFactory.decodeFile(pathName, options); // options.inSampleSize是圖片的壓縮比,例如原來大小是100*100,options.inSampleSize為1,則不變, // options.inSampleSize為2,則壓縮成50*50 options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);// 重新設定options.inJustDecodeBounds為false,不能修改option options.inJustDecodeBounds = false; // 根據options重新載入圖片 Bitmap src = BitmapFactory.decodeFile(pathName, options); return src; } public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, intreqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { inSampleSize *= 2; } } return inSampleSize; }