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"; }