前言
本文非原创,大佬的基础上进行修改和调试,下面三种方式我都测试过。感谢大佬们分享。
好记性不如烂笔头
总结
- 如果只获取高宽,推荐使用BitmapFactory.Options
- 如果要加载图片和获取高宽,推荐使用Glide
- 如果只是加载jpg图片,可以考虑ExifInterface,否则不推荐
正文
下面分别简单介绍一下 三种方式
使用BitmapFactory.Options
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; //不进行解码标志
BitmapFactory.decodeFile(path, options);
options.inJustDecodeBounds = false;
int width = options.outWidth;
int height = options.outHeight;使用Glide
需要使用开源框架Glide
Glide.with(getActivity()).load(mImageUrl).asBitmap()
        .priority(Priority.LOW)
        .diskCacheStrategy(DiskCacheStrategy.RESULT)
        .into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
            @Override
            public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                int imageWidth = bitmap.getWidth();
                int imageHeight = bitmap.getHeight();
                mPhotoView.setImageBitmap(bitmap);
            }
            @Override
            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                super.onLoadFailed(e, errorDrawable);
            }
        });
对图片格式没有特别的限制,而且还支持大图和长图的显示。
使用ExifInterface
try {
    ExifInterface exifInterface = new ExifInterface(path);
    int rotation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
    int width = exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 0);
    int height = exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 0);
    // 图片被旋转90或者270,使用时候将width、height换下
    if (rotation == ExifInterface.ORIENTATION_ROTATE_90 || rotation == ExifInterface.ORIENTATION_ROTATE_270) {
    } else {
    }
} catch (Exception e) {
    e.printStackTrace();
}
测试中发现这个对jpg格式的图片ok,对png或gif格式的的图片不太友好。
不推荐使用此方式。
