Java tutorial
//package com.java2s; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class Main { public static boolean compressAndSaveBitmap(File input, File output, int width, int height, int quality) { Bitmap bitmap = getSmallBitmap(input.getAbsolutePath(), width, height); return saveBitmap(bitmap, output.getAbsolutePath(), quality); } public static Bitmap getSmallBitmap(String filePath, int width, int height) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, width, height); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(filePath, options); } @SuppressWarnings("ResultOfMethodCallIgnored") public static boolean saveBitmap(Bitmap bitmap, String filePath, int quality) { boolean result = false; FileOutputStream fileOutputStream = null; try { File file = new File(filePath); if (file.exists()) file.delete(); fileOutputStream = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fileOutputStream); fileOutputStream.flush(); result = true; } catch (IOException ignored) { } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException ignored) { } } } return result; } public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; } }