代码如下,喜欢的给点热心值哦!
[Java] 纯文本查看 复制代码 package com.tools.comparison.service.impl;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.IIOImage;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.ImageWriteParam;
import java.awt.Graphics2D;
public class ImageCompressorImageIo {
public static void main(String[] args) {
String sourceFilePath = "C:\\*****\\1111.jpg";
String compressedFilePath = "C:\\*****\\out1111--22222.jpg";
String watermarkPath = "C:\\*****\\*****.png";
/*File watermarkFile = new File(watermarkPath);
BufferedImage watermarkImage = ImageIO.read(watermarkFile);*/
//压缩质量(0.0 ~ 1.0)
float quality = 0.5f;
LocalDateTime beginBuildMapTime = LocalDateTime.now();
compressImage(sourceFilePath, compressedFilePath, quality);
LocalDateTime endBuildMapTime = LocalDateTime.now();
long ss = Duration.between(beginBuildMapTime,endBuildMapTime).toMillis();
System.out.println("ImageIo耗时:"+ ss+ "毫秒");
}
public static void compressImage(String sourceFilePath, String compressedFilePath, float quality) {
BufferedImage originalImage = null;
ImageWriter writer = null;
FileImageOutputStream out = null;
try {
Path path = Paths.get(sourceFilePath);
String fileType = Files.probeContentType(path);
System.out.println("文件类型:"+fileType);
String fileName = path.getFileName().toString();
String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
System.out.println("文件后缀:"+fileSuffix);
// 读取原始图片
File sourceFile = new File(sourceFilePath);
originalImage = ImageIO.read(sourceFile);
// 创建压缩后的写入器
// ImageIO.getImageWritersByFormatName() JPEG、PNG、BMP 方法可以根据格式名称获取对应的 ImageWriter 对象
writer = ImageIO.getImageWritersBySuffix(fileSuffix).next();
// writer = ImageIO.getImageWritersByFormatName(fileSuffix).next();
// 设置输出参数,控制压缩质量(只有JPEGImageWriteParam格式能控制压缩参数)
ImageWriteParam writeParam = writer.getDefaultWriteParam();
if (writeParam instanceof JPEGImageWriteParam) {
// 如果是 JPEG 格式,设置压缩质量为 0.8
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writeParam.setCompressionQuality(quality);
}
// 创建压缩后的图片
File compressedFile = new File(compressedFilePath);
out = new FileImageOutputStream(compressedFile);
writer.setOutput(out);
// 创建用于写入的 IIOImage 对象
IIOImage image = new IIOImage(originalImage, null, null);
writer.write(null, image, writeParam);
} catch (IOException e) {
System.out.println("压缩图片失败:" + e.getMessage());
} finally {
// 释放资源
if (originalImage != null) {
originalImage.flush();
}
if (writer != null) {
writer.dispose();
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
System.out.println("关闭文件流失败:" + e.getMessage());
}
}
}
}
}
|