1. 程式人生 > >安卓圖片壓縮處理的終極方法,適用於各種機型

安卓圖片壓縮處理的終極方法,適用於各種機型


//直接呼叫getimage,引數為:路徑、寬、高

public static Bitmap getimage(String pathName, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        // 若要對圖片進行壓縮,必須先設定OptioninJustDecodeBoundstrue才能進行Option的修改
        options.inJustDecodeBounds = true;
        // 第一次
decodeFile是獲取到options.outHeightoptions.outWidth BitmapFactory.decodeFile(pathName, options); // options.inSampleSize是圖片的壓縮比,例如原來大小是100*100options.inSampleSize1,則不變, // options.inSampleSize2,則壓縮成50*50 options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// 重新設定options.inJustDecodeBoundsfalse,不能修改option options.inJustDecodeBounds = false; // 根據options重新載入圖片 Bitmap src = BitmapFactory.decodeFile(pathName, options); return src; } public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int
reqHeight) { 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; }