Android获取网络图片的宽高

有时我们需要在加载显示网络图片前拿到图片的宽高对控件做些处理,比如针对过长的图片只显示部分,点击后在展示全图,那么怎样拿到网络图片的宽高呢?

方式一、使用HttpURLConnection + BitmapFactory.Options

通过使用BitmapFactory.Options只解码边界的方式,避免将整个图片资源加载到内存而导致获取过多图片宽高时造成OOM

public static void getPicSize(String url, onPicListener listener) {
        mPicFixThreadPool.execute(() -> {
            HttpURLConnection connection;
            try {
                connection = (HttpURLConnection) new URL(url).openConnection();
                InputStream inputStream = connection.getInputStream();
                int[] imageSize = getImageSize(inputStream);
                mMainHandler.post(() -> listener.onImageSize(imageSize[0], imageSize[1]));
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    private static int[] getImageSize(InputStream is) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(is, null, options);
        int[] size = new int[2];
        size[0] = options.outWidth;
        size[1] = options.outHeight;
        LogUtil.i("--------------------width = " + size[0] + ",height = " + size[1]+"--------------------");
        return size;
    }

 public interface onPicListener {
        void onImageSize(int width, int height);
    }

方式二、使用Glide

Glide.with(mContext).asBitmap().load(url).into(object : BitmapImageViewTarget(imageView) {
    override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
        super.onResourceReady(resource, transition)
        val width = resource.width
        val height = resource.height
        Log.i("kkk", "width = $width,height = $height")
    }
})

方式三

待添加...

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值