package com.dsh.guns.modular.system.util;
|
|
import lombok.Getter;
|
|
import javax.imageio.ImageIO;
|
import java.awt.image.BufferedImage;
|
import java.io.IOException;
|
import java.io.InputStream;
|
import java.net.URL;
|
import java.net.URLConnection;
|
|
public class ImageUtils {
|
|
/**
|
* 获取图片的尺寸(宽高)
|
*
|
* @param imageUrl 图片的URL地址
|
* @return 包含图片宽高的Dimension对象
|
* @throws IOException 如果URL无效、读取超时、图片格式不支持或图片损坏
|
*/
|
public static Dimension getImageDimensions(String imageUrl) throws IOException {
|
URL url = new URL(imageUrl);
|
URLConnection connection = url.openConnection();
|
// 设置连接和读取超时时间(单位:毫秒)
|
connection.setConnectTimeout(5000);
|
connection.setReadTimeout(5000);
|
|
try (InputStream inputStream = connection.getInputStream()) {
|
BufferedImage image = ImageIO.read(inputStream);
|
if (image == null) {
|
throw new IOException("Unsupported image format or corrupted image");
|
}
|
return new Dimension(image.getWidth(), image.getHeight());
|
}
|
}
|
|
/**
|
* 封装图片宽高的内部类
|
*/
|
@Getter
|
public static class Dimension {
|
private final int width;
|
private final int height;
|
|
public Dimension(int width, int height) {
|
this.width = width;
|
this.height = height;
|
}
|
|
@Override
|
public String toString() {
|
return "Dimension{width=" + width + ", height=" + height + "}";
|
}
|
|
/**
|
* 展示类型 1 横屏 2 竖屏
|
* @return
|
*/
|
public Integer getDisplayType(){
|
if (width > height) {
|
return 1;
|
} else {
|
return 2;
|
}
|
}
|
}
|
|
// 示例用法
|
public static void main(String[] args) {
|
try {
|
Dimension dimension = getImageDimensions("https://we-park-life.oss-cn-beijing.aliyuncs.com/img/e4ef2672d1a6456f9cd680ce51cf3a6e.jpg");
|
System.out.println(dimension);
|
System.out.println(dimension.getDisplayType());
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
}
|