Skip to content

Commit

Permalink
Fix Android image rotation issue when compressing gallery and camera …
Browse files Browse the repository at this point in the history
…images (#379)

When using the image compression options, the returned resized image orientation differed from the original image. This caused selected images to often be rotated.

Original issue thread:
#379
  • Loading branch information
bonesyblue committed Apr 17, 2019
1 parent 326e180 commit 765b9c8
Showing 1 changed file with 24 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Environment;
import android.util.Log;

Expand Down Expand Up @@ -30,6 +32,14 @@ File resize(String originalImagePath, int maxWidth, int maxHeight, int quality)
int width = original.getWidth();
int height = original.getHeight();

// Use original image exif orientation data to preserve image orientation for the resized bitmap
ExifInterface originalExif = new ExifInterface(originalImagePath);
int originalOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);

Matrix rotationMatrix = new Matrix();
int rotationAngleInDegrees = getRotationInDegreesForOrientationTag(originalOrientation);
rotationMatrix.postRotate(rotationAngleInDegrees);

float ratioBitmap = (float) width / (float) height;
float ratioMax = (float) maxWidth / (float) maxHeight;

Expand All @@ -43,6 +53,7 @@ File resize(String originalImagePath, int maxWidth, int maxHeight, int quality)
}

Bitmap resized = Bitmap.createScaledBitmap(original, finalWidth, finalHeight, true);
resized = Bitmap.createBitmap(resized, 0, 0, finalWidth, finalHeight, rotationMatrix, true);
File resizeImageFile = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), UUID.randomUUID() + ".jpg");

Expand All @@ -56,6 +67,19 @@ File resize(String originalImagePath, int maxWidth, int maxHeight, int quality)
return resizeImageFile;
}

int getRotationInDegreesForOrientationTag(int orientationTag) {
switch(orientationTag){
case ExifInterface.ORIENTATION_ROTATE_90:
return 90;
case ExifInterface.ORIENTATION_ROTATE_270:
return -90;
case ExifInterface.ORIENTATION_ROTATE_180:
return 180;
default:
return 0;
}
}

File compressImage(final ReadableMap options, final String originalImagePath, final BitmapFactory.Options bitmapOptions) throws IOException {
Integer maxWidth = options.hasKey("compressImageMaxWidth") ? options.getInt("compressImageMaxWidth") : null;
Integer maxHeight = options.hasKey("compressImageMaxHeight") ? options.getInt("compressImageMaxHeight") : null;
Expand Down

0 comments on commit 765b9c8

Please sign in to comment.