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

前言

通过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来获取图片的旋转方向。获取到方向之后,就可以通过方向的值来获取正确的图片宽高。完整代码如下:

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;
    }
}

其他

Android让人头疼的OOM,造成OOM的原因之一就是图片,现在的手机像素越来越高,随便一张图片都是好几M,甚至几十M,这样的照片加载到app,可想而知,随便加载几张图片,手机内存就不够用了,自然而然就造成了OOM,所以,Android的图片压缩异常重要。这里,我推荐一款开源框架——Luban
(https://codechina.csdn.net/mirrors/curzibn/luban?utm_source=csdn_github_accelerator)

依赖

implementation 'top.zibin:Luban:1.1.3'

你可能感兴趣的:(解决Android通过BitmapFactory获取图片宽高度相反的问题)