Skip to content

Instantly share code, notes, and snippets.

@douglaskayama
Last active February 11, 2018 13:07
Show Gist options
  • Select an option

  • Save douglaskayama/31f6f4e7affae14cf77f to your computer and use it in GitHub Desktop.

Select an option

Save douglaskayama/31f6f4e7affae14cf77f to your computer and use it in GitHub Desktop.
Reduce a Bitmap on Android
// Disclaimer: this wasn't tested, it's just for teaching the way to a friend,
// maybe there are some bugs.
public void reduceBitmap(String sourcePath, String destinationPath) {
// Adjust width and height to your needs
int targetW = 800;
int targetH = 600;
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(sourcePath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(sourcePath, bmOptions);
final int BUFFER_SIZE = 1024 * 8;
try {
file.createNewFile();
FileOutputStream fos = new FileOutputStream(destinationPath);
final BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER_SIZE);
bitmap.compress(CompressFormat.JPEG, 70, bos); // Adjust quality to your needs
bos.flush();
} catch (FileNotFoundException | IOException e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment