原文:https://blog.csdn.net/simonchi/article/details/55098709
Thumbnailator 不推薦使用文件流操作
?fromPic:讀取文件的路徑宝剖;toPic:處理后保存文件的路徑的烁。
?相關(guān)參數(shù):size(寬度,?高度)??
1. 單個圖片等比例縮放
File file = new File("c:\\test.png");
Thumbnails.of(new FileInputStream(file)).scale(3.0).toFile(new File(toPic));
3.0是一個double類型的數(shù)字,縮放比例诈闺,大于1就是變大渴庆,小于1就是縮小
2. 批量產(chǎn)生縮略圖
Thumbnails.of(new File("D:\\pics").listFiles()).scale(0.2).outputFormat("png")
.toFiles(Rename.PREFIX_DOT_THUMBNAIL);
3. 控制圖片質(zhì)量,圖片尺寸不變
Thumbnails.of(fromPic).scale(1f).outputQuality(0.25f).toFile(toPic);
outputQuality 就是用來控制圖片質(zhì)量的
4. 給圖片加水印
Thumbnails.of(fromPic).scale(0.8).watermark(Positions.BOTTOM_RIGHT,ImageIO.read(waterPic), 0.5f).outputQuality(0.8f).toFile(toPic);
fromPic是原圖,waterPic是水印圖片襟雷,toPic是生成后的圖片
5. 旋轉(zhuǎn)圖片
Thumbnails.of(fromPic).scale(0.5).rotate(90).toFile(toPic);?
rotate:旋轉(zhuǎn)角度
6. 圖片裁剪
Thumbnails.of(fromPic).sourceRegion(Positions.CENTER,300,300).scale(1.0).toFile(toPic);sourceRegion :獲取原圖相關(guān)區(qū)域? 圖片居中 300*300的區(qū)域? ?
//指定坐標(biāo)?? 不按照比例刃滓,指定大小
Thumbnails.of( fromPic ) .sourceRegion(600,?500,?400,?400).size(200,?200).keepAspectRatio(false).toFile( toPic);?
7.?轉(zhuǎn)化圖像格式?
Thumbnails.of( fromPic) .size(1280,?1024).outputFormat("png").toFile( toPic);???
8.?輸出到OutputStream?
Thumbnails.of(fromPic).size(1280,?1024).toOutputStream(new?FileOutputStream(toPic));??
9.?輸出到BufferedImage?
BufferedImage thumbnail? =?Thumbnails.of(fromPic).size(1280,?1024).asBufferedImage();? ImageIO.write(thumbnail,"jpg",?new?File(toPic));? ?
需要注意的是,對于CMYK模式的圖像耸弄,由于JDK的Bug咧虎,目前還不能夠處理,會出以下異常:
引用:
javax.imageio.IIOException: Unsupported Image Type?
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:1063)?
at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:1034)?
at javax.imageio.ImageReader.read(ImageReader.java:940)?
at net.coobird.thumbnailator.tasks.io.FileImageSource.read(Unknown Source)
引用:
?javax.imageio.IIOException: Incompatible color conversion?
??? at com.sun.imageio.plugins.jpeg.JPEGImageReader.checkColorConversion(JPEGImageReader.java:973)
引用:
?java.lang.IllegalArgumentException: Numbers of source Raster bands and source color space components do not match?
at java.awt.image.ColorConvertOp.filter(ColorConvertOp.java:482)?
at com.sun.imageio.plugins.jpeg.JPEGImageReader.acceptPixels(JPEGImageReader.java:1268)?
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readImage(Native Method)?
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:1236)?
at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:1039)?
??? at javax.imageio.ImageReader.read(ImageReader.java:939)
這些問題可以JAI.create()來代替ImageIO.read()解決计呈。而高清圖的內(nèi)存溢出OOM問題只能使用ImageMagick轉(zhuǎn)換了砰诵。