Java tutorial
//package com.java2s; //License from project: Open Source License import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.ExifInterface; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class Main { public static void compressFileIfNeeded(String filePath) { File f = new File(filePath); Bitmap bitmap; bitmap = BitmapFactory.decodeFile(filePath); int MAX_IMAGE_SIZE = 1000 * 1024; int streamLength = (int) f.length(); if (streamLength > MAX_IMAGE_SIZE) { int compressQuality = 105; ByteArrayOutputStream bmpStream = new ByteArrayOutputStream(); while (streamLength >= MAX_IMAGE_SIZE && compressQuality > 5) { try { bmpStream.flush();//to avoid out of memory error bmpStream.reset(); } catch (IOException e) { e.printStackTrace(); } compressQuality -= 5; bitmap.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpStream); byte[] bmpPicByteArray = bmpStream.toByteArray(); streamLength = bmpPicByteArray.length; Log.d("test upload", "Quality: " + compressQuality); Log.d("test upload", "Size: " + streamLength); } FileOutputStream fo; try { f.delete(); f = new File(filePath); fo = new FileOutputStream(f); fo.write(bmpStream.toByteArray()); fo.flush(); fo.close(); ExifInterface exif = new ExifInterface(f.getAbsolutePath()); exif.setAttribute(ExifInterface.TAG_ORIENTATION, "6"); exif.saveAttributes(); } catch (IOException e) { e.printStackTrace(); } } } }