Java进行图片压缩

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

public class ImageCompressor {

    public static void main(String[] args) {
        String inputImagePath = "input.jpg";
        String outputImagePath = "output.jpg";

        File inputFile = new File(inputImagePath);
        BufferedImage inputImage = null;

        try {
            inputImage = ImageIO.read(inputFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //调用compressImage方法进行图片压缩
        BufferedImage outputImage = compressImage(inputImage, 0.5f);

        //将压缩后的图片写入磁盘文件
        File outputFile = new File(outputImagePath);
        try {
            ImageIO.write(outputImage, "jpg", outputFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static BufferedImage compressImage(BufferedImage sourceImage, float quality) {
        int width = sourceImage.getWidth();
        int height = sourceImage.getHeight();

        BufferedImage compressedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics2D graphics = compressedImage.createGraphics();
        graphics.drawRenderedImage(sourceImage, null);
        graphics.dispose();

        ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
        ImageWriteParam writeParam = writer.getDefaultWriteParam();

        //设置图像质量参数
        writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        writeParam.setCompressionQuality(quality);

        //写入压缩后的图片到输出流
        File tempFile = new File("temp.jpg");
        try {
            ImageOutputStream outputStream = ImageIO.createImageOutputStream(tempFile);
            writer.setOutput(outputStream);
            IIOImage image = new IIOImage(compressedImage, null, null);
            writer.write(null, image, writeParam);
            outputStream.close();
            writer.dispose();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //读取压缩后的图片并返回
        BufferedImage outputImage = null;
        try {
            outputImage = ImageIO.read(tempFile);
            tempFile.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outputImage;
    }
}

Java提供了许多图片压缩的类库和工具,其中最常用的是ImageIO和ImageIO.write()方法。上面是一个简单的Java代码示例,演示如何使用ImageIO类来进行图片压缩。

在这个例子中,我们将输入文件路径和输出文件路径指定为“input.jpg”和“output.jpg”。然后使用ImageIO类的read()方法从输入文件中读取原始图像。接下来,我们调用compressImage()方法对图像进行压缩,其中quality参数指定了所需的压缩质量。最后,我们将压缩后的图像保存到输出文件中。

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