shikeying
2024-01-11 3b67e947e36133e2a40eb2737b15ea375e157ea0
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
package com.walker.infrastructure.utils;
 
import com.walker.infrastructure.ApplicationRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import javax.imageio.ImageIO;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
 
public class ImageUtils {
 
    protected static final Logger logger = LoggerFactory.getLogger(ImageUtils.class);
 
    /***
     * 按指定的比例缩放图片
     *
     * @param sourceImagePath
     * 源地址
     * 改变大小后图片的地址
     * 缩放比例,如1.2
     * @return 返回压缩后的新文件路径
     * @date 2023-11-02
     */
    public static String scaleImage4Jpg(String sourceImagePath, double maxWidth) {
        File file = new File(sourceImagePath);
        BufferedImage bufferedImage = null;
 
        try {
            bufferedImage = ImageIO.read(file);
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if(width <= maxWidth){
                return sourceImagePath;
            }
            double scale = maxWidth / width;
            logger.debug("scale = {}", scale);
            width = parseDoubleToInt(width * scale);
            height = parseDoubleToInt(height * scale);
 
            Image image = bufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
 
            BufferedImage outputImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics graphics = outputImage.getGraphics();
            graphics.drawImage(image, 0, 0, null);
            graphics.dispose();
 
            String destinationPath = FileUtils.getThumbNailsName(sourceImagePath);
            ImageIO.write(outputImage, IMAGE_JPG, new File(destinationPath));
            return destinationPath;
 
        } catch (IOException e) {
            logger.error("scaleImage方法压缩图片时出错:" + e.getMessage() + ", file=" + sourceImagePath, e);
            throw new ApplicationRuntimeException("压缩图片错误:" + sourceImagePath, e);
        } finally {
 
        }
    }
 
    private static int parseDoubleToInt(double sourceDouble) {
        int result = 0;
        return  (int) sourceDouble;
    }
 
    public static final String IMAGE_JPG = "jpg";
}