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")
    }
})

方式三

待添加...

发布了57 篇原创文章 · 获赞 26 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/Ever69/article/details/104235785