可以通过以下代码获取网络图片的宽高:
public void getImageSize(final String imageUrl) {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; // 设置为true,只获取图片大小
BitmapFactory.decodeStream(inputStream, null, options);
int width = options.outWidth;
int height = options.outHeight;
Log.d("ImageSize", "Width: " + width + ", Height: " + height);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
以上代码中,先通过URL
对象打开网络连接,然后获取输入流,设置BitmapFactory.Options
对象的inJustDecodeBounds
为true
,这样就只会计算出图片的宽高信息,不会加载整张图片,最后关闭输入流即可。
要获取网络图片的宽高,可以使用Android中的BitmapFactory类。
首先,你需要从URL获取图片的输入流,并将其解码为一个Bitmap对象:
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
然后,你可以使用Bitmap对象的getWidth()和getHeight()方法获取它的宽度和高度:
int width = bitmap.getWidth();
int height = bitmap.getHeight();
最后,别忘了在完成后关闭输入流和连接:
input.close();
connection.disconnect();
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/159591.html