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参数指定了所需的压缩质量。最后,我们将压缩后的图像保存到输出文件中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值