Java tutorial
//package com.java2s; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; public class Main { private static Context context; public static Bitmap decodeSampledBitmapFromResource(int resId, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(context.getResources(), resId, options); // Calculate inSampleSize float sampleSize = calculateInSampleSize(options, reqWidth, reqHeight); Log.d("----> Sample Size:", sampleSize + ""); if (sampleSize < 1) { // return a scaled UP version of image Bitmap bg = BitmapFactory.decodeResource(context.getResources(), resId); Bitmap scaledBitmap = Bitmap.createScaledBitmap(bg, (int) (bg.getWidth() / sampleSize), (int) (bg.getHeight() / sampleSize), true); bg.recycle(); return scaledBitmap; } else { // return a scaled DOWN version of image options.inSampleSize = Math.round(sampleSize); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(context.getResources(), resId, options); } } public static float calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; float inSampleSize = 1; if (height >= reqHeight || width >= reqWidth) { if (width > height) { inSampleSize = height / (float) reqHeight; } else { inSampleSize = width / (float) reqWidth; } } else { inSampleSize = Math.min((float) width / reqWidth, (float) height / reqHeight); } return inSampleSize; } }