Java – Android cannot load images in the correct orientation from the gallery

Android cannot load images in the correct orientation from the gallery… here is a solution to the problem.

Android cannot load images in the correct orientation from the gallery

I’m loading an image from a gallery via the bitmap API, but the orientation of the image is different from the orientation I saved. Somewhere in stackoverflow, I read that I needed to get the positioning values, and then rotated the matrix. I tried, but my direction shows 0 from the exif interface.

        int desiredImageWidth = 310;   pixels
        int desiredImageHeight = 518;  pixels

Log.i("FA", "Image Loading "+strFileName);
        BitmapFactory.Options o = new BitmapFactory.Options();
        Bitmap newImage = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(strFileName, o), 
                                                   desiredImageWidth, 
                                                   desiredImageHeight, 
                                                   false);

Bitmap finalBmp = getCorrectOrientedBitmap(strFileName,newImage);

Bitmap myBitmap32 = finalBmp.copy(Bitmap.Config.ARGB_8888, true);

Mat matImg = Utils.bitmapToMat(myBitmap32);

My main targeting features are

:

    private Bitmap getCorrectOrientedBitmap(String filename,Bitmap Source) throws IOException{

Bitmap rotatedBitmap = null;
    ExifInterface exif = new ExifInterface(filename);
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);

Matrix matrix = new Matrix();
    Log.i("FA", "orientation "+orientation);
    switch(orientation)
    {
    case 6:
        matrix.postRotate(90);
        break;
    case 3:
        matrix.postRotate(180);
        break;
    case 8:
        matrix.postRotate(270);
        break;
    }
    rotatedBitmap = Bitmap.createBitmap(Source, 0, 0, Source.getWidth(), Source.getHeight(), matrix, true);

return rotatedBitmap;
}

Solution

If you return 0 from getAttributeInt, then I think it just means that there is no orientation information stored in your “rotated” image. You can independently double-check with an online tool or download a good image viewer to find out.

Have you tried this code on other devices? Could it be that your test equipment doesn’t have orientation labels saved?

This page has some good sample code to do what you want to do, Maybe you can find some improvements there too.

Related Problems and Solutions