制作图片缩略图的Groovy脚本

本文介绍了一个使用 Java 编写的图片缩略图生成器,该程序能够批量处理指定目录下的图片文件,生成固定尺寸的缩略图,并保持原始图片的比例不变。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->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, 
00null); // 绘制缩小后的图
    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)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值