在 Java 中,可以使用不同的方式来压缩图片以达到指定的大小。下面将介绍两种常用的方式:使用 Java 标准库和使用第三方库 ImageIO,以及使用第三方库 Thumbnails。每种方式都会包括详细的步骤流程和相应的代码示例。
步骤流程:
示例代码:
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
public class ImageCompression {
public static void compressImage(File inputImage, File outputImage, float quality) throws IOException {
BufferedImage image = ImageIO.read(inputImage);
// Create a ByteArrayOutputStream to hold the compressed image data
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// Get the ImageIO writer for JPEG format
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
// Set the compression quality parameter
ImageWriteParam params = writer.getDefaultWriteParam();
params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
params.setCompressionQuality(quality);
// Write the compressed image data to the ByteArrayOutputStream
ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputStream);
writer.setOutput(imageOutputStream);
writer.write(null, new IIOImage(image, null, null), params);
// Write the compressed data to the output file
try (OutputStream fileOutputStream = new FileOutputStream(outputImage)) {
outputStream.writeTo(fileOutputStream);
}
// Clean up resources
writer.dispose();
imageOutputStream.close();
}
public static void main(String[] args) throws IOException {
File inputImage = new File("input.jpg");
File outputImage = new File("output_compressed.jpg");
float compressionQuality = 0.5f; // Adjust the quality as needed
compressImage(inputImage, outputImage, compressionQuality);
}
}
步骤流程:
Maven 依赖:
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.14</version>
</dependency>
Gradle 依赖:
implementation 'net.coobird:thumbnailator:0.4.14'
示例代码:
import net.coobird.thumbnailator.Thumbnails;
import java.io.File;
import java.io.IOException;
public class ThumbnailCompression {
public static void compressImage(File inputImage, File outputImage, double scale, float quality) throws IOException {
Thumbnails.of(inputImage)
.scale(scale)
.outputQuality(quality)
.toFile(outputImage);
}
public static void main(String[] args) throws IOException {
File inputImage = new File("input.jpg");
File outputImage = new File("output_thumbnail.jpg");
double scale = 0.5; // Scale down to 50%
float compressionQuality = 0.5f; // Adjust the quality as needed
compressImage(inputImage, outputImage, scale, compressionQuality);
}
}
这两种方法都可以用来压缩图片至指定大小,具体的实现选择取决于你的项目需求和偏好。