解决Android通过BitmapFactory获取图片宽高度相反的问题

2,352 阅读1分钟

前言

常见通过BitmapFactory获取图片的宽高度的代码如下:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile("{IMAGE_PATH}", options);
int width = options.outWidth;
int height = options.outHeight;

使用上述代码,在图片未旋转的情况下得到的结果是正确的。但是如果图片需要旋转90度或者270度才能正确显示时,上述代码获取的宽度则是相反的(及获取到的宽度实际上为图片的高度,高度亦然)。

所以,我们需要通过判断图片显示需要旋转的度数来确定图片真实的宽高。

在Android中可以通过ExifInterface来获取图片的旋转方向。具体代码如下:

try
{  
    ExifInterface exifInterface = new ExifInterface({IMAGE_PATH});  
    int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); return orientation;
}
catch (IOException e)
{
    e.printStackTrace();  
    return ExifInterface.ORIENTATION_NORMAL;
}

获取到方向之后,就可以通过方向的值来获取正确的图片宽高。完整代码如下:

public static Size getImageSize(String imageLocalPath)
{
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeFile("{IMAGE_PATH}", options);
    int width = options.outWidth;
    int height = options.outHeight;
    
    int orientation = getImageOrientation(imageLocalPath);
    switch(orientation)
    {
        case ExifInterface.ORIENTATION_ROTATE_90:
        case ExifInterface.ORIENTATION_ROTATE_270:
        {
            return new Size(height, width);
        }
        default:
        {
            return new Size(width, height);
        }
    }
}

public static int getImageOrientation(String imageLocalPath)
{
    try
    {  
        ExifInterface exifInterface = new ExifInterface({IMAGE_PATH});  
        int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); return orientation;
`   }
    catch (IOException e)
    {
        e.printStackTrace();  
        return ExifInterface.ORIENTATION_NORMAL;
    }
}