Skip to content

Instantly share code, notes, and snippets.

@jibbo
Created June 12, 2018 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jibbo/85a04bc148cbb7e153f5bc6dd1408225 to your computer and use it in GitHub Desktop.
Save jibbo/85a04bc148cbb7e153f5bc6dd1408225 to your computer and use it in GitHub Desktop.
[Android] Save JPEG with lesser quality the bigger it is, especially useful to reduce image upload time.
private static final int MB = 1000000; // 1MB in bytes
private static final int MIN_SIZE = 3; // in MB
private static final int MAX_SIZE = 20; // in MB
private static final int MAX_QUALITY = 100;
private static final int MIN_QUALITY = 10;
private static final int NORMAL_QUALITY = 90;
/**
* Gets a bitmap and saves it as jpeg.
*
* @return the handle of the saved file.
*/
public static File saveBitmapOnDisk(Context context, String fileName, Bitmap bitmap) throws IOException {
// can I write on the cache? IOException otherwise.
final File file = FileUtils.findBestStoringPlace(context, fileName);
final int sizeInMb = bitmap.getByteCount() / MB;
final int quality;
if (BuildConfig.DEBUG || sizeInMb > MAX_SIZE) {
quality = MIN_QUALITY;
} else if (sizeInMb <= MIN_SIZE) {
quality = NORMAL_QUALITY;
} else {
// In order to reduce upload time we need to reduce the image size.
// Therefore, quality should be inversely proportional to the image size
// (bigger images=>worse quality), the following formula is obtained
// from this proportion: MAX_SIZE : MAX_QUALITY = sizeInMb : quality
quality = MAX_QUALITY - ((sizeInMb * MAX_QUALITY) / MAX_SIZE);
}
// overwrites the old file if it exists.
final OutputStream os = new FileOutputStream(file, false);
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, os);
os.flush();
os.close();
return file;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment