WEB开发网
开发学院软件开发Java 制作图片缩略图的Groovy脚本 阅读

制作图片缩略图的Groovy脚本

 2009-09-22 00:00:00 来源:WEB开发网   
核心提示:importjavax.imageio.ImageIO;importjava.io.File;importjava.io.IOException;importjava.awt.image.BufferedImage;importjava.awt.*;defcreateThumbnail(Fileinput,Fileou

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)
}

Tags:制作 图片 缩略

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接