thumbnailator 图片缩放

 Thumbnailator是一个用来生成图像缩略图的 Java类库,通过很简单的代码即可生成图片缩略图,也可直接对一整个目录的图片生成缩略图。

       有了这玩意,就不用在费心思使用Image I/O API,Java 2D API等等来生成缩略图了。

Thumbnailator的下载地址:

http://code.google.com/p/thumbnailator/downloads/list

好了,直接上代码:

  
  
  1. /**  
  2.      *   
  3.      * @throws IOException   
  4.      * @brief 生成缩略图简单实例   
  5.      *  
  6.      */ 
  7.     public static void simple() throws IOException{  
  8.             //需要转换的文件为桌面上的1.png  
  9.             Thumbnails.of("C:/Documents and Settings/Administrator/桌面/1.png")  
  10.             /*  
  11.              * forceSize,size和scale必须且只能调用一个  
  12.              */ 
  13. //          .forceSize(400, 400)  //生成的图片一定为400*400  
  14.             /*  
  15.              * 若图片横比200小,高比300小,不变  
  16.              * 若图片横比200小,高比300大,高缩小到300,图片比例不变  
  17.              * 若图片横比200大,高比300小,横缩小到200,图片比例不变  
  18.              * 若图片横比200大,高比300大,图片按比例缩小,横为200或高为300  
  19.              */ 
  20.             .size(200300)     
  21.             .outputFormat("png"//生成图片的格式为png  
  22.             .outputQuality(0.8f) //生成质量为80%  
  23. //          .scale(0.5f)  //缩小50%  
  24.             //输出到桌面5文件  
  25.             .toFile("C:/Documents and Settings/Administrator/桌面/2");  
  26.     }  
  27.       
  28.     /**  
  29.      *   
  30.      * @throws IOException   
  31.      * @brief 生成旋转的缩略图  
  32.      *  
  33.      */ 
  34.     public static void rotate() throws IOException{  
  35.         Thumbnails.of("C:/Documents and Settings/Administrator/桌面/1.png")  
  36.         //顺时针旋转90度  
  37.         .rotate(90)  
  38.         .scale(0.8f)  
  39.         .toFile("C:/Documents and Settings/Administrator/桌面/3");  
  40.     }  
  41.       
  42.     /**  
  43.      *   
  44.      * @brief 生成带水印的图片  
  45.      *  
  46.      * @throws IOException  
  47.      */ 
  48.     public static void watermark() throws IOException {  
  49.         Thumbnails.of("C:/Documents and Settings/Administrator/桌面/1.png")  
  50.         //水印在右下角,50%透明度,水印图片为桌面上的logo.gif  
  51.         .watermark(Positions.BOTTOM_RIGHT,ImageIO.read(new File("C:/Documents and Settings/Administrator/桌面/logo.gif")),0.5f)  
  52.         .scale(0.8f)  
  53.         .toFile("C:/Documents and Settings/Administrator/桌面/4");  
  54.     } 

使用到的图片1.png:

 

logo.gif:

生成的缩略图2.png: 

生成的缩略图3.png:

生成的缩略图4.png:

本文出自 “雪飘七月” 博客,请务必保留此出处http://xuepiaoqiyue.blog.51cto.com/4391594/803834

猜你喜欢

转载自woshixushigang.iteye.com/blog/1576928