Skip to content

Instantly share code, notes, and snippets.

@alizahid
Last active October 1, 2018 18:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alizahid/91d8b100b708ee37d00f to your computer and use it in GitHub Desktop.
Save alizahid/91d8b100b708ee37d00f to your computer and use it in GitHub Desktop.
Image resize and fix orientation in Java
private static Bitmap getImage(Context context, String name, int quality) throws IOException {
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), name);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getAbsolutePath(), options);
float ratio = (float) options.outWidth / (float) options.outHeight;
boolean isLandscape = options.outWidth > options.outHeight;
int width;
int height;
if (isLandscape) {
width = quality * 15;
height = Math.round(width / ratio);
} else {
height = quality * 15;
width = Math.round(height / ratio);
}
int sampleSize = 1;
if (options.outWidth > width || options.outHeight > height) {
if (options.outWidth > options.outHeight) {
sampleSize = Math.round((float) options.outHeight / (float) height);
} else {
sampleSize = Math.round((float) options.outWidth / (float) width);
}
}
options.inSampleSize = sampleSize;
options.inScaled = false;
options.inJustDecodeBounds = false;
Bitmap image = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
image = Bitmap.createScaledBitmap(image, width, height, true);
ExifInterface exif = new ExifInterface(file.getAbsolutePath());
float angle;
switch (exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)) {
case ExifInterface.ORIENTATION_ROTATE_90:
angle = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
angle = 180;
break;
default:
case ExifInterface.ORIENTATION_NORMAL:
angle = 0;
break;
}
if (angle > 0) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
image = Bitmap.createBitmap(image, 0, 0, width, height, matrix, true);
}
return image;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment