生成缩略图~java
话不多说直接上代码:
public class ImageUtil {
/**
* 生成缩略图
* @param input 资源文件
* @param outputPath 生成缩略图文件夹路径
* @param shrink 缩放比例
* @throws IOException
*/
public static File shrinkPic(File input, String outputPath, double shrink) throws IOException {
String name = input.getName();
// 读取原始图像文件
// 创建BufferedImage对象来存储原始图像数据
BufferedImage originalImage = ImageIO.read(input);
// 设置新的图像大小(这里将图像缩小为原来的1/2)
int scaledWidth = (int) (originalImage.getWidth() * shrink);
int scaledHeight = (int) (originalImage.getHeight() * shrink);
// 创建目标图像对象并指定新的大小
BufferedImage resizedImage = new BufferedImage(scaledWidth, scaledHeight, originalImage.getType());
// 获得Graphics2D对象以进行操作
Graphics graphics = resizedImage.getGraphics();
// 调用drawImage()方法进行缩放处理
graphics.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
// 释放Graphics2D对象
graphics.dispose();
// 输出结果到文件或显示在界面上等等...
File output = new File(outputPath + File.separator + name);
ImageIO.write(resizedImage, "jpg", output);
return output;
}
/**
* 生成缩略图
* @param input 资源文件输入流
* @param outputPath 生成缩略图文件夹路径
* @param shrink 缩放比例
* @throws IOException
*/
public static File shrinkPic(InputStream input, String outputPath, double shrink) throws IOException {
// 读取原始图像文件
// 创建BufferedImage对象来存储原始图像数据
BufferedImage originalImage = ImageIO.read(input);
// 设置新的图像大小(这里将图像缩小为原来的1/2)
int scaledWidth = (int) (originalImage.getWidth() * shrink);
int scaledHeight = (int) (originalImage.getHeight() * shrink);
// 创建目标图像对象并指定新的大小
BufferedImage resizedImage = new BufferedImage(scaledWidth, scaledHeight, originalImage.getType());
// 获得Graphics2D对象以进行操作
Graphics graphics = resizedImage.getGraphics();
// 调用drawImage()方法进行缩放处理
graphics.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
// 释放Graphics2D对象
graphics.dispose();
// 输出结果到文件或显示在界面上等等...
File output = new File(outputPath);
if (!output.getParentFile().getParentFile().exists()) {
output.getParentFile().mkdirs();
}
if (!output.getParentFile().exists()) {
output.mkdirs();
}
ImageIO.write(resizedImage, "jpg", output);
return output;
}
}
上面两个方法都是返回缩略后的图片文件,不同的是一个传的文件File,一个传的是文件流。
还没有评论,来说两句吧...