java 生成图片缩略图_Java为图片生成缩略图
时间: 2024-05-01 08:22:09 浏览: 168
Java图片裁剪和生成缩略图的实例方法
Java可以使用ImageIO类和BufferedImage类来生成图片缩略图。
以下是一个示例代码,它将加载指定的图片,将其缩小至指定的大小,并将其保存为新文件:
```java
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageThumbnail {
public static void main(String[] args) {
try {
// Load the original image from file
BufferedImage originalImage = ImageIO.read(new File("original.jpg"));
// Calculate the new image size
int thumbnailWidth = 100;
int thumbnailHeight = (int) (((double) thumbnailWidth / (double) originalImage.getWidth()) * originalImage.getHeight());
// Create a new, blank image of the appropriate size and type
BufferedImage thumbnailImage = new BufferedImage(thumbnailWidth, thumbnailHeight, BufferedImage.TYPE_INT_RGB);
// Scale the original image to the new size using Graphics2D
Graphics2D g2d = thumbnailImage.createGraphics();
g2d.drawImage(originalImage, 0, 0, thumbnailWidth, thumbnailHeight, null);
g2d.dispose();
// Save the scaled image to file
ImageIO.write(thumbnailImage, "jpg", new File("thumbnail.jpg"));
} catch (IOException ex) {
System.err.println("Error generating thumbnail: " + ex.getMessage());
}
}
}
```
这个示例代码会将原始图片 "original.jpg" 缩小至 100 像素宽度,并将其高度按比例缩小。缩略图将保存为 "thumbnail.jpg"。
阅读全文