Skip to content

Instantly share code, notes, and snippets.

@aviadmini
Created September 9, 2016 21:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aviadmini/4be34097dfdb842ae066fae48501ed41 to your computer and use it in GitHub Desktop.
Save aviadmini/4be34097dfdb842ae066fae48501ed41 to your computer and use it in GitHub Desktop.
Android snippet: EXIF orientation to Bitmap transformation Matrix
import android.graphics.Matrix;
import android.media.ExifInterface;
// Some reference: https://msdn.microsoft.com/library/windows/apps/windows.storage.fileproperties.photoorientation
public class ExifToMat {
public static Matrix fromOrientation(final int pExifOrientation) {
Matrix matrix = new Matrix();
switch (pExifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_270: {
matrix.postRotate(270);
break;
}
case ExifInterface.ORIENTATION_ROTATE_180: {
matrix.postRotate(180);
break;
}
case ExifInterface.ORIENTATION_ROTATE_90: {
matrix.postRotate(90);
break;
}
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: {
matrix.preScale(-1.0f, 1.0f);
break;
}
case ExifInterface.ORIENTATION_FLIP_VERTICAL: {
matrix.preScale(1.0f, -1.0f);
break;
}
case ExifInterface.ORIENTATION_TRANSPOSE: {
matrix.preRotate(-90);
matrix.preScale(-1.0f, 1.0f);
break;
}
case ExifInterface.ORIENTATION_TRANSVERSE: {
matrix.preRotate(90);
matrix.preScale(-1.0f, 1.0f);
break;
}
}
return matrix;
}
private ExifToMat() {}
}
// Usage
final File file = getJpegFile();
final Bitmap raw = BitmapFactory.decodeFile(file.getAbsolutePath());
Matrix matrix = null;
try {
final ExifInterface exif = new ExifInterface(file.getAbsolutePath());
final int exifOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
matrix = ExifToMat.fromOrientation(exifOrientation);
} catch (final IOException e) {
e.printStackTrace();
}
// At this point the matrix is the transformation matrix for image file with EXIF orientation attribute
// So you can create a correctly transformed Bitmap now
final Bitmap transformedBitmap = Bitmap.createBitmap(raw, 0, 0, raw.getWidth(), raw.getHeight(), matrix, true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment