Programming Tips - Android: rotate a JPG image based on EXIF info

Date: 2020jul10 OS: Android Language: Java Keywords: JPEG Q. Android: rotate a JPG image based on EXIF info A. These typically come from phone cameras.
Bitmap rotateIfNecessary(final Bitmap bmOrig, final String filename) { ExifInterface exif; try { exif = new ExifInterface(filename); } catch (IOException ex) { Log.i(Main.LOG_TAG, "rotateIfNecessary: Could not new ExifInterface"); return bmOrig; } final int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1); Matrix matrix = new Matrix(); switch(orientation) { case ExifInterface.ORIENTATION_ROTATE_90: matrix.postRotate(90F); break; case ExifInterface.ORIENTATION_ROTATE_180: matrix.postRotate(180F); break; case ExifInterface.ORIENTATION_ROTATE_270: matrix.postRotate(270F); break; default: return bmOrig; } Log.i(Main.LOG_TAG, "rotateIfNecessary: Rotating " + filename); final Bitmap bmRotated = Bitmap.createBitmap(bmOrig, 0, 0, bmOrig.getWidth(), bmOrig.getHeight(), matrix, true); bmOrig.recycle(); return bmRotated; }