等比例缩放多个图片

该代码示例展示了如何使用Java的ImageIO和BufferedImage类来等比例缩放图片,确保所有图片在缩放后宽高相等且不失真。程序首先读取指定目录下的图片文件,然后应用缩放方法,最后保存调整大小后的图片到新的目录。
摘要由CSDN通过智能技术生成

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


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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值