有時我們需要在加載顯示網絡圖片前拿到圖片的寬高對控件做些處理,比如針對過長的圖片只顯示部分,點擊後在展示全圖,那麼怎樣拿到網絡圖片的寬高呢?
方式一、使用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")
}
})
方式三
待添加...