Thumbnailator是一个开源的图片缩略图工具,使用简单方便,支持各种方式的缩略图生成,目前最新的版本为0.4.8,Thumbnailator在github上的地址 https://github.com/coobird/thumbnailator
下面展示下几种生成缩略图的方法。
/**
* Created by 水煮蜗牛 on 2016/8/3.
*/
public class ThumbnailsTest {
public static void main(String[] args) {
ThumbnailsTest.picZoom("F:/ship.jpg");
}
/**
* 缩放图片
*/
public static void picZoom(String filePath) {
try {
File file = new File(filePath);
/**
* 指定大小进行缩放
* 若图片横比200小,高比300小,不变
* 若图片横比200小,高比300大,高缩小到300,图片比例不变
* 若图片横比200大,高比300小,横缩小到200,图片比例不变
* 若图片横比200大,高比300大,图片按比例缩小,横为200或高为300
*/
Thumbnails.of(filePath)
.size(200, 300)
.toFile(file.getAbsolutePath() + "_200x300.jpg");
/**
* 按照比例进行缩放
* scale(比例)
* */
Thumbnails.of(filePath)
.scale(0.25f)
.toFile(file.getAbsolutePath() + "_25%.jpg");
/**
* 不按照比例,指定大小进行缩放
* keepAspectRatio(false) 默认是按照比例缩放的
* */
Thumbnails.of(filePath)
.size(200, 200)
.keepAspectRatio(false)
.toFile(file.getAbsolutePath() + "_200x200.jpg");
/**
* 输出图片到流对象
*
* */
OutputStream os = new FileOutputStream(file.getAbsolutePath() + "_OutputStream.png");
Thumbnails.of(filePath)
.size(1280, 1024)
.toOutputStream(os);
/**
* 输出图片到BufferedImage
* **/
BufferedImage thumbnail = Thumbnails.of(filePath)
.size(1280, 1024)
.asBufferedImage();
ImageIO.write(thumbnail, "jpg", new File(file.getAbsolutePath()+"_BufferedImage.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
这几种常用的生成缩略图方法记熟了就可以应对大多数的情况了,有兴趣的小伙伴可以试试看。。