前言

本文非原创,大佬的基础上进行修改和调试,下面三种方式我都测试过。感谢大佬们分享。

好记性不如烂笔头

总结

  1. 如果只获取高宽,推荐使用BitmapFactory.Options
  2. 如果要加载图片和获取高宽,推荐使用Glide
  3. 如果只是加载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,使用时候将widthheight换下
    if (rotation == ExifInterface.ORIENTATION_ROTATE_90 || rotation == ExifInterface.ORIENTATION_ROTATE_270) {

    } else {

    }
} catch (Exception e) {
    e.printStackTrace();
}

测试中发现这个对jpg格式的图片ok,对png或gif格式的的图片不太友好。

不推荐使用此方式。

参考文章

  1. Android获得图片宽高的三种方法
  2. Glide加载大图长图

相关文章

暂无评论

none
暂无评论...