以下是使用Java自带的ImageIO类压缩图片的实现代码:

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageCompressor {
    
    public static void main(String[] args) {
        File inputFile = new File("input.jpg");
        File outputFile = new File("output.jpg");
        int maxWidth = 800; // 设置压缩后的最大宽度
        int maxHeight = 600; // 设置压缩后的最大高度
        float quality = 0.8f; // 设置压缩质量,范围为0~1,值越小压缩后的图片越模糊
        
        try {
            BufferedImage inputImage = ImageIO.read(inputFile);
            int originalWidth = inputImage.getWidth();
            int originalHeight = inputImage.getHeight();
            int newWidth = originalWidth;
            int newHeight = originalHeight;
            
            // 根据最大宽度和高度计算压缩后的宽度和高度
            if (originalWidth > maxWidth) {
                newWidth = maxWidth;
                newHeight = (newWidth * originalHeight) / originalWidth;
            }
            if (newHeight > maxHeight) {
                newHeight = maxHeight;
                newWidth = (newHeight * originalWidth) / originalHeight;
            }
            
            // 压缩图片并保存到输出文件
            BufferedImage outputImage = new BufferedImage(newWidth, newHeight, inputImage.getType());
            outputImage.getGraphics().drawImage(inputImage, 0, 0, newWidth, newHeight, null);
            ImageIO.write(outputImage, "jpg", outputFile);
            
            // 设置压缩质量并保存到输出文件
            ImageIO.write(outputImage, "jpg", outputFile);
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在上述代码中,我们首先读取输入文件的原始图片,并计算压缩后的宽度和高度。然后使用BufferedImage类创建一个压缩后的图片,并将原始图片绘制到压缩后的图片中。最后使用ImageIO类将压缩后的图片保存到输出文件中。同时,我们还可以通过设置ImageIO.write()方法的第三个参数来控制压缩质量,范围为0~1,值越小压缩后的图片越模糊。

使用Java自带的ImageIO类压缩图片 实现

原文地址: https://www.cveoy.top/t/topic/bRjg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录