Java tutorial
//package com.java2s; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; public class Main { public static Bitmap decodeSampleBitMapFromResource(Context context, int resId, int reqWidth, int reqHeight) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(context.getResources(), resId, options); options = sampleBitmapOptions(context, options, reqWidth, reqHeight); Bitmap bm = BitmapFactory.decodeResource(context.getResources(), resId, options); Log.e("xxx", bm.getByteCount() + ""); return bm; } public static BitmapFactory.Options sampleBitmapOptions(Context context, BitmapFactory.Options options, int reqWidth, int reqHeight) { int targetDensity = context.getResources().getDisplayMetrics().densityDpi; // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); double xSScale = ((double) options.outWidth) / ((double) reqWidth); double ySScale = ((double) options.outHeight) / ((double) reqHeight); double startScale = xSScale > ySScale ? xSScale : ySScale; options.inScaled = true; options.inDensity = (int) (targetDensity * startScale); options.inTargetDensity = targetDensity; options.inJustDecodeBounds = false; options.inPreferredConfig = Bitmap.Config.RGB_565; return options; } public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image 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; } }