正确获取手机本地图片的宽度和高度

获取手机本地图片的宽度和高度,我们通常使用以下方法:

 final BitmapFactory.Options options = new BitmapFactory.Options();
 options.inJustDecodeBounds = true;
 BitmapFactory.decodeFile(filePath, options);
 int width= options.outWidth;
 int height=options.outHeight;

但是在一些手机机型上如三星手机,拍照后图片可能会进行旋转,如旋转90度,如果采用上面的代码获取的宽高值可能是反的,这时就需要获取图片的旋转角度,然后根据旋转角度来获取图片的宽高,直接上代码:

    //获取手机本地图片的宽度和高度
    private Pair<Integer,Integer> getImageWidthHeight(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        int width= options.outWidth;
        int height=options.outHeight;
        int orientation=ExifInterface.ORIENTATION_NORMAL;
        try {
            ExifInterface exifInterface = new ExifInterface(filePath);
            orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
            case ExifInterface.ORIENTATION_ROTATE_270:
                width=options.outHeight;
                height=options.outWidth;
                break;
        }
        return new Pair<>(width,height);
    }

EXIF:可交换图像文件格式(英语:Exchangeable image file format,官方简称Exif),是专门为数码相机的照片设定的,可以记录数码照片的属性信息和拍摄数据,只有JPEG格式的图片才会携带exif数据,像PNG,WebP这类的图片就不会有这些数据。

在Android下,可以通过ExifInterface类来获取图片的信息如曝光时间,图片宽度,图片高度,设备品牌,旋转角度等信息。使用的demo图片如下,图片的宽高为3024*4032,可自行测试

猜你喜欢

转载自www.cnblogs.com/rainboy2010/p/12557015.html