java 如何缩小图片
缩小图片的方法
在Java中缩小图片可以通过多种方式实现,以下介绍几种常见的方法:
使用java.awt.Image和Graphics2D
通过Image.getScaledInstance()或Graphics2D的绘制方法可以实现图片缩放:

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ImageResizer {
public static void resize(String inputImagePath, String outputImagePath, int scaledWidth, int scaledHeight) throws Exception {
BufferedImage inputImage = ImageIO.read(new File(inputImagePath));
BufferedImage outputImage = new BufferedImage(scaledWidth, scaledHeight, inputImage.getType());
Graphics2D g2d = outputImage.createGraphics();
g2d.drawImage(inputImage, 0, 0, scaledWidth, scaledHeight, null);
g2d.dispose();
ImageIO.write(outputImage, "jpg", new File(outputImagePath));
}
}
使用Thumbnailator库
Thumbnailator是一个专门用于缩略图生成的Java库,使用简单:
import net.coobird.thumbnailator.Thumbnails;
public class ThumbnailExample {
public static void resize(String inputPath, String outputPath, int width, int height) throws Exception {
Thumbnails.of(inputPath)
.size(width, height)
.toFile(outputPath);
}
}
使用ImageIO和插值算法
通过设置渲染提示可以控制缩放质量:

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class HighQualityResizer {
public static void resize(String inputPath, String outputPath, int width, int height) throws Exception {
BufferedImage originalImage = ImageIO.read(new File(inputPath));
BufferedImage resizedImage = new BufferedImage(width, height, originalImage.getType());
Graphics2D g = resizedImage.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(originalImage, 0, 0, width, height, null);
g.dispose();
ImageIO.write(resizedImage, "jpg", new File(outputPath));
}
}
保持宽高比的缩放
如果需要保持原始图片的宽高比,可以计算适当的尺寸:
public static void resizeWithAspectRatio(String inputPath, String outputPath, int maxWidth, int maxHeight) throws Exception {
BufferedImage originalImage = ImageIO.read(new File(inputPath));
int originalWidth = originalImage.getWidth();
int originalHeight = originalImage.getHeight();
float ratio = Math.min((float)maxWidth/originalWidth, (float)maxHeight/originalHeight);
int newWidth = (int)(originalWidth * ratio);
int newHeight = (int)(originalHeight * ratio);
BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, originalImage.getType());
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, newWidth, newHeight, null);
g.dispose();
ImageIO.write(resizedImage, "jpg", new File(outputPath));
}
性能考虑
对于大批量图片处理,建议:
- 使用缓冲技术减少I/O操作
- 考虑多线程处理
- 选择合适的插值算法(双线性或双三次通常质量较好)
格式支持
上述方法支持常见图片格式如JPG、PNG等,具体取决于ImageIO注册的插件。如需更多格式支持,可添加额外依赖如TwelveMonkeys ImageIO。






