Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java 图片压缩

作者:古枕清风   发布日期:2025-05-31   浏览:95

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 compressImage(String inputFilePath, String outputFilePath, int targetWidth, int targetHeight) {
        try {
            // 读取原始图片
            File inputFile = new File(inputFilePath);
            BufferedImage originalImage = ImageIO.read(inputFile);

            // 创建一个具有指定宽度和高度的缓冲图像
            BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, originalImage.getType());
            Graphics2D g2d = resizedImage.createGraphics();

            // 设置抗锯齿
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.drawImage(originalImage, 0, 0, targetWidth, targetHeight, null);
            g2d.dispose();

            // 将压缩后的图片写入文件
            File outputFile = new File(outputFilePath);
            ImageIO.write(resizedImage, "jpg", outputFile);

            System.out.println("图片压缩完成!");
        } catch (IOException e) {
            System.out.println("图片压缩失败: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        // 示例调用
        compressImage("input.jpg", "output.jpg", 800, 600);
    }
}

解释说明

  1. 导入必要的包

    • javax.imageio.ImageIO:用于读取和写入图像。
    • java.awt.*java.awt.image.BufferedImage:用于处理图像。
    • java.io.Filejava.io.IOException:用于文件操作和异常处理。
  2. compressImage 方法

    • 接受四个参数:输入文件路径、输出文件路径、目标宽度和目标高度。
    • 使用 ImageIO.read 读取原始图片。
    • 创建一个新的 BufferedImage 对象,设置其宽度和高度为目标尺寸。
    • 使用 Graphics2D 绘制并调整原始图片的大小。
    • 设置抗锯齿以提高图像质量。
    • 使用 ImageIO.write 将压缩后的图片保存到指定路径。
  3. main 方法

    • 提供一个示例调用,将 input.jpg 压缩为 800x600 的 output.jpg

希望这段代码对你有帮助!

上一篇:java object

下一篇:java equalsignorecase

大家都在看

java连接数据库的代码

ubuntu 卸载java

java读取excel中的图片

java新建

java sort用法

java collections.sort

java file类的方法

java 判断

java时间数据类型

java实体类转json字符串

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站