??×÷í???????í?μ?Groovy??±?
ê±??:2011-01-15 BlogJava oúáé
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)??{
???????????????? //??±£3??-à′′óD?
???????????????? width??=??realWidth;
???????????????? height??=??realHeight;
???????? }??else??if??((length??*??realHeight)??/??realWidth??>??length)??{
???????????????? //??°′??êμ?ê???èà′?1??
???????????????? //???1??oóμ??í
???????????????? width??=??(length??*??realWidth)??/??realHeight;
???????????????? //???1??oóμ????è
???????????????? height??=??length;
???????? }??else??{
???????????????? //??°′êμ?ê?í?èà′?1??
???????????????? //???1??oóμ??í
???????????????? width??=??length;
???????????????? //???1??oóμ????è
???????????????? 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);??//????????D?oóμ?í?
???????? 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)
}
|