Java tutorial
//package com.java2s; import java.io.File; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; import android.os.Build; import android.text.TextUtils; public class Main { private static final int UNCONSTRAINED = -1; @SuppressWarnings("deprecation") public static int[] getBitmapSize(File file, int targetWidth, int targetHeight) { if (null != file && file.exists() && file.isFile() && file.canRead()) { String path = file.getAbsolutePath(); Options opts = new Options(); if (targetWidth > 0 && targetHeight > 0) { opts.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, opts); opts.inSampleSize = computeSampleSize(opts, Math.min(targetWidth, targetHeight), targetWidth * targetHeight); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { opts.inInputShareable = true; opts.inPurgeable = true; } } BitmapFactory.decodeFile(path, opts); return new int[] { opts.outWidth, opts.outHeight }; } return null; } public static int[] getBitmapSize(String path, int targetWidth, int targetHeight) { if (TextUtils.isEmpty(path)) { return null; } if (path.matches("^\\w+$")) { return null; } return getBitmapSize(new File(path), targetWidth, targetHeight); } public static int computeSampleSize(Options options, int minSideLength, int maxNumOfPixels) { int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels); int roundedSize; if (initialSize <= 8) { roundedSize = 1; while (roundedSize < initialSize) { roundedSize <<= 1; } } else { roundedSize = (initialSize + 7) / 8 * 8; } return roundedSize; } private static int computeInitialSampleSize(Options options, int minSideLength, int maxNumOfPixels) { double w = options.outWidth; double h = options.outHeight; int lowerBound = (maxNumOfPixels == UNCONSTRAINED) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels)); int upperBound = (minSideLength == UNCONSTRAINED) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength)); if (upperBound < lowerBound) { // return the larger one when there is no overlapping zone. return lowerBound; } if ((maxNumOfPixels == UNCONSTRAINED) && (minSideLength == UNCONSTRAINED)) { return 1; } else if (minSideLength == UNCONSTRAINED) { return lowerBound; } else { return upperBound; } } }