2007年4月20日星期五

ImgRsz 批量图片大小转换Perl脚本

干活的时候发现有一堆图片改大小....Linux下没找到称手的工具...但Perl在...

在CPAN找了个Imlib2...顺手写了个练练手

功能很简单 -d 指定目录 -w 宽度 -h 高度 ,宽度和高度有一个没设置就等比转换,写完才发现作为一个Perl程序已经写的太长了...还打算加入多个指定文件和指定目录的操作......但暂时凑或吧
#!/usr/bin/perl -w

use strict;

use Getopt::Long;

use Image::Imlib2;

my $resualt;

my $file;

my $height=0;

my $width=0;

my $dir='';

my $subdir='thumbles/';

my $image;

my $help=0;

my $version='ImgRsz Version 0.1 By Icat with Imlib2';

sub usage(){

version();

print ' -d -dir dir'."\n";

print ' -w -width width'."\n";

print ' -h -height height'."\n";

print ' -help print this info'."\n";

};

sub version(){

print $version."\n";

};

$resualt=GetOptions('d|dir=s'=>\$dir,'w|width=i'=>\$width,'h|height=i'=>\$height,'help'=>\$help);

if (($dir eq '')or($help eq 1)or($width eq 0 and $height eq 0)){

usage();

exit;

};



(substr($dir,-1,1)eq '/') ?($dir=$dir):($dir.="/");

print "processing dir ".$dir."\n";

opendir DH, $dir or die "open dir error!$dir :$!";

system "mkdir",$dir.$subdir if not -e $dir.$subdir;

foreach $file (readdir DH){

if($file=~/.+\.jpg/i) {

print "processing file ".$dir.$file."\n";

$image = Image::Imlib2->load($dir.$file);

if($width eq 0){

$width=$height*$image->get_width/$image->get_height;

};

if($height eq 0){

$height=$width*$image->get_height/$image->get_width;

};

my $imageScaled=$image->create_scaled_image($width,$height);

$imageScaled->save($dir.$subdir.$file);

}else{

print "$file not processed\n";

}

};

closedir DH;