Java tutorial
//package com.java2s; //License from project: Open Source License import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Build; import java.io.InputStream; import java.lang.reflect.Field; public class Main { private static final int DECODE_BUFFER_SIZE = 16 * 1024; private static final int DENSITY_240 = 240; private static final int DENSITY_400 = 400; private static final float SCALE_FACTOR = 0.8f; private static final float SCALE_FACTOR_2 = 0.7f; private static final Bitmap.Config DEFAULT_BITMAP_CONFIG = Bitmap.Config.RGB_565; public static Bitmap decodeBitmap(Context context, int resId) { checkParam(context); return BitmapFactory.decodeResource(context.getResources(), resId, getBitmapOptions(context)); } public static Bitmap decodeBitmap(Context context, String pathName) { checkParam(context); return BitmapFactory.decodeFile(pathName, getBitmapOptions(context)); } public static Bitmap decodeBitmap(Context context, InputStream is) { checkParam(context); checkParam(is); return BitmapFactory.decodeStream(is, null, getBitmapOptions(context)); } private static <T> void checkParam(T param) { if (param == null) throw new NullPointerException(); } private static BitmapFactory.Options getBitmapOptions(Context context) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inScaled = true; options.inPreferredConfig = DEFAULT_BITMAP_CONFIG; options.inPurgeable = true; options.inInputShareable = true; options.inJustDecodeBounds = false; options.inTempStorage = new byte[DECODE_BUFFER_SIZE]; if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) { Field field = null; try { field = BitmapFactory.Options.class.getDeclaredField("inNativeAlloc"); field.setAccessible(true); field.setBoolean(options, true); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } int displayDensityDpi = context.getResources().getDisplayMetrics().densityDpi; float displayDensity = context.getResources().getDisplayMetrics().density; int density = 0; if (displayDensityDpi > DENSITY_240 && displayDensityDpi <= DENSITY_400 && displayDensity > 1.5f) { density = (int) (displayDensityDpi * SCALE_FACTOR); } else if (displayDensityDpi > DENSITY_400 && displayDensity > 2.5f) { density = (int) (displayDensityDpi * SCALE_FACTOR_2); } if (density == 0) return options; options.inDensity = density; options.inTargetDensity = density; return options; } }