Sometimes we need to show the first network to get the picture width and height of the picture controls do processing load, such as for display only part of the picture too long, after clicking to show the whole map, then how to get the picture of the network aspect of it?
A mode using HttpURLConnection + BitmapFactory.Options
OOM caused by using BitmapFactory.Options only way to decode the border to avoid the entire picture will be loaded into memory resources and result in getting too much width and height of the picture
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);
}
Second way, use 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")
}
})
Three ways
To be added ...