Java tutorial
//package com.java2s; //License from project: Apache License import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.media.ThumbnailUtils; import java.io.File; public class Main { private static String IMAGE_TYPT_BMP = "bmp"; private static String IMAGE_TYPT_JPG = "jpg"; private static String IMAGE_TYPT_JPEG = "jpeg"; private static String IMAGE_TYPT_PNG = "png"; private static String IMAGE_TYPT_GIF = "gif"; private static Bitmap adjustDisplayImage(String path, int width, int hight) { BitmapFactory.Options opts = getBitmapOptions(path); int srcWidth = opts.outWidth; int srcHeight = opts.outHeight; Bitmap compressedBitmap = null; Bitmap thumbnailBitmap = null; try { thumbnailBitmap = getThumbnail(path, width, hight); if (null == thumbnailBitmap) { return null; } compressedBitmap = ThumbnailUtils.extractThumbnail(thumbnailBitmap, width, hight, 1); } catch (Error e) { return null; } finally { if (thumbnailBitmap != null) { thumbnailBitmap.recycle(); thumbnailBitmap = null; } } return compressedBitmap; } private static BitmapFactory.Options getBitmapOptions(String path) { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, opts); return opts; } private static Bitmap getThumbnail(String filePath, int targetW, int targetH) { Bitmap bitmap = null; File file = new File(filePath); String fileName = file.getName(); if (fileName.lastIndexOf(".") < 0) { return bitmap; } String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1); if (fileExtension.equalsIgnoreCase(IMAGE_TYPT_BMP) || fileExtension.equalsIgnoreCase(IMAGE_TYPT_JPG) || fileExtension.equalsIgnoreCase(IMAGE_TYPT_JPEG) || fileExtension.equalsIgnoreCase(IMAGE_TYPT_PNG) || fileExtension.equalsIgnoreCase(IMAGE_TYPT_GIF)) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); int bitmapRealWidth = options.outWidth; int bitmapRealHeight = options.outHeight; options.outWidth = targetW; if (bitmapRealWidth > 0) { options.outHeight = bitmapRealHeight * targetW / bitmapRealWidth; } options.inJustDecodeBounds = false; if (targetW > 0) { options.inSampleSize = bitmapRealWidth / targetW; } options.inPurgeable = true; options.inInputShareable = true; options.inPreferredConfig = Config.ARGB_4444; bitmap = BitmapFactory.decodeFile(filePath, options); } return bitmap; } }