等比例缩放多个图片

最新做了一个等比例缩放多个图片,保证所有图片宽高相等并不失真的功能,现将代码粘贴出来。


import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ScaleImage {
    public static void main(String[] args) throws IOException {
        // 需要合并的图片文件列表
        List<String> imageFiles = new ArrayList<>();
        File file = new File("E:\\ysj");
        File[] files = file.listFiles();

        for (int i = 0; i < files.length; i++) {
            imageFiles.add(files[i].getName());
            System.err.println(files[i].getName());
        }
        for (String imageFile : imageFiles) {
            //加载图片
            File f = new File("E:\\ysj\\" + imageFile);
            BufferedImage image = ImageIO.read(f);
            BufferedImage imag = scaleImage(image, 2400, 4600);
            String[] split = imageFile.split("\\.");
            //保存图片
            File targetFile = new File("E:\\newYsj\\"+ split[0] + ".jpg");
            ImageIO.write(imag, "jpg", targetFile);
        }
    }

    // 等比例缩放图片
    private static BufferedImage scaleImage(BufferedImage img, int maxWidth, int maxHeight) {
        int width = img.getWidth();
        int height = img.getHeight();

        // 计算缩放比例
        double scale = Math.min((double)maxWidth/width, (double)maxHeight/height);

        // 缩放后的图片宽度和高度
        int newWidth = (int)(width * scale);
        int newHeight = (int)(height * scale);

        // 创建缩放后的图片
        BufferedImage scaledImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = scaledImage.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.drawImage(img, 0, 0, newWidth, newHeight, null);
        g2d.dispose();

        return scaledImage;
    }
}

你可能感兴趣的:(java,开发语言)