mitao
2025-04-03 71fca447b76d88b45ef5c24b47a9428a517c4499
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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();
        }
    }
}