缩略图代表网页上或计算机中图片经压缩方式处理后的小图 ,其中通常会包含指向完整大小的图片的超链接。缩略图用于在 Web 浏览器中更加迅速地装入图形或图片较多的网页。今天,我们就开始java中图像的缩略图的学习。thumbnailator框架的使用: Java三方---->Thumbnailator框架的使用
使用jdk自带bufferedImage
项目结构如下:
一、 JDKZoomImage.java
packagecom.huhx.jdk;importjava.awt.Graphics;importjava.awt.image.BufferedImage;importjava.io.File;importjava.io.IOException;importjavax.imageio.ImageIO;/*** writer: huhx*/
public classJDKZoomImage {
public voidzoomImage() {
BufferedImage bufferedImage= null;
File file= new File("image/huhx.jpg");if(file.canRead()) {try{
bufferedImage=ImageIO.read(file);
bufferedImage= zoomInImage(bufferedImage, 5);
ImageIO.write(bufferedImage,"JPG", new File("image/zoomHuhx.jpg"));
}catch(IOException e) {
e.printStackTrace();
}
}
}private BufferedImage zoomInImage(BufferedImage bufferedImage, inttimes) {int width = bufferedImage.getWidth() /times;int height = bufferedImage.getHeight() /times;
BufferedImage newImage= newBufferedImage(width, height, bufferedImage.getType());
Graphics graphics=newImage.getGraphics();
graphics.drawImage(bufferedImage,0, 0, width, height, null);
graphics.dispose();returnnewImage;
}public static voidmain(String[] args) {newJDKZoomImage().zoomImage();
}
}
二、 结果如下,生成图片zoomHuhx.jpg
huhx.jpg 1366 * 768 398KB
zoomHuhx.jpg 273*153 18.4KB
使用thumbnailator框架
ThumbnailatorImage.java的内容如下:
packagecom.huhx.jdk;importjava.io.File;importjava.io.IOException;importnet.coobird.thumbnailator.Thumbnails;importnet.coobird.thumbnailator.name.Rename;/***@authorhuhx*/
public classThumbnailatorImage {//根据缩放比缩放图片
public voidzoomImageWithScale() {try{
Thumbnails.of(new File("image/huhx.jpg").listFiles()).scale(0.2).outputFormat("jpg").toFiles(Rename.PREFIX_DOT_THUMBNAIL);
}catch(IOException e) {
e.printStackTrace();
}
}//根据固定大小缩放图片
public voidzoomImageWithSize() {try{
Thumbnails.of(new File("image/huhx.jpg").listFiles()).size(640, 480).outputFormat("jpg").toFiles(Rename.PREFIX_DOT_THUMBNAIL);
}catch(IOException e) {
e.printStackTrace();
}
}public static voidmain(String[] args) {
ThumbnailatorImage image= newThumbnailatorImage();
image.zoomImageWithScale();
image.zoomImageWithSize();
}
}