程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 制作圖片縮略圖的Groovy腳本

制作圖片縮略圖的Groovy腳本

編輯:關於JAVA

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import java.awt.*;
def createThumbnail(File input, File output, int length) throws IOException {
     if (!input.exists()) {
         throw new RuntimeException("input file not exists!");
     }
     if (!output.exists()) {
         output.createNewFile();
     }
     BufferedImage srcImage = ImageIO.read(input);
     int realWidth = srcImage.getWidth(null);
     int realHeight = srcImage.getHeight(null);
     int width, height;
     if (realWidth < length && realHeight < length) {
         // 保持原來大小
         width = realWidth;
         height = realHeight;
     } else if ((length * realHeight) / realWidth > length) {
         // 按照實際高度來壓縮
         // 壓縮後的寬
         width = (length * realWidth) / realHeight;
         // 壓縮後的高度
         height = length;
     } else {
         // 按實際寬度來壓縮
         // 壓縮後的寬
         width = length;
         // 壓縮後的高度
         height = (length * realHeight) / realWidth;
     }

     Image newImage = srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
     BufferedImage targetImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
     Graphics g = targetImage.getGraphics();
     g.drawImage(newImage, 0, 0, null); // 繪制縮小後的圖
     g.dispose();
     ImageIO.write(targetImage, "jpeg", output);
}

def dir = new File("d:/var/wormser/sample")
dir.eachFile{ f->
     def name = f.name;
     println name
     newFileName = name.replaceAll(/^([a-zA-Z0-9_]+)\.([a-zA-Z0-9]+)$/, "\$1_tb.jpg")
     def newFile = new File(dir.getAbsolutePath() + File.separator + newFileName)
     println newFileName
     createThumbnail(f, newFile, 160)
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved