Skip to content

Instantly share code, notes, and snippets.

@tomogoma
Created March 18, 2017 08:25
Show Gist options
  • Save tomogoma/788e3b775dd611c9226f8e17781a0f0c to your computer and use it in GitHub Desktop.
Save tomogoma/788e3b775dd611c9226f8e17781a0f0c to your computer and use it in GitHub Desktop.
Android code to rotate an image based on exif information
// imports
public class ImageRotator {
public static Bitmap rotateImage(String path) throws IOException {
Bitmap bitmap = BitmapFactory.decodeFile(path);
return rotateImage(bitmap);
}
public static Bitmap rotateImage(Bitmap bitmap) throws IOException {
int rotate = 0;
ExifInterface exif;
exif = new ExifInterface(path);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
Matrix matrix = new Matrix();
matrix.postRotate(rotate);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
}
}
@pikaboo
Copy link

pikaboo commented May 22, 2019

what is path in new ExifInterface(path);

@towcar
Copy link

towcar commented Jun 4, 2019

@pikaboo that is the String of the file's path

@daupawar
Copy link

public static Bitmap rotateImage(String path) throws IOException {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        return rotateImage(bitmap, path);
    }
 public static Bitmap rotateImage(Bitmap bitmap, String path) throws IOException {
        int rotate = 0;
        ExifInterface exif;
        exif = new ExifInterface(path);
............

@manishktx
Copy link

thanks

@vicmaple
Copy link

Wouldn't it be simpler to to get rid of the first rotateImage() and check if the bitmap object in the second rotateImage() is valid like so?

/* 🦀 rotateImage(String path) is dead 🦀 */

public static Bitmap rotateImage(Bitmap bitmap, String path) throws IOException {

        if(bitmap == null){ //if bitmap in param is null, use the path and put something in it!
            bitmap = BitmapFactory.decodeFile(path);
        }

        int rotate = 0;
        [...]
}

@tomogoma
Copy link
Author

That would work I suppose. The intention of having both functions was for the code to be explicit about the input the function is taking (whether it's bitmap or path - we cannot consume both). This separation of functions makes it more readable. Combining into one function works, but you lose that intuitive ability of a consumer to understand that we need either bitmap or path but not both

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment