import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
public class ImageCompressor {
public static void compressImage(String inputImagePath, String outputImagePath, int targetWidth, int targetHeight) {
try {
// 读取原始图片
File inputFile = new File(inputImagePath);
BufferedImage originalImage = ImageIO.read(inputFile);
// 创建一个新的缓冲图像对象,用于存储压缩后的图像
BufferedImage compressedImage = new BufferedImage(targetWidth, targetHeight, originalImage.getType());
// 获取Graphics2D对象,用于绘制压缩后的图像
Graphics2D g2d = compressedImage.createGraphics();
// 设置仿射变换,保持图像比例缩放
AffineTransform at = new AffineTransform();
at.scale((double) targetWidth / originalImage.getWidth(), (double) targetHeight / originalImage.getHeight());
g2d.drawRenderedImage(originalImage, at);
// 释放资源
g2d.dispose();
// 将压缩后的图像写入输出文件
File outputFile = new File(outputImagePath);
ImageIO.write(compressedImage, "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);
}
}
BufferedImage
、ImageIO
、Graphics2D
等。Graphics2D
对象来绘制压缩后的图像,同时通过AffineTransform
保持图像的比例缩放。compressImage
方法进行图片压缩。希望这段代码能帮助你实现Java中的图片压缩功能!
上一篇:java 字符串格式化
下一篇:java 字符串长度
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站