package hello;
use nginx;
use Gearman::Client;
my $client = Gearman::Client->new();
$client->job_servers("192.168.102.207:4730");
sub handler {
my $r = shift; # $r->send_http_header("image/jpeg");
return OK if $r->header_only;
my $rpath = '/tmp/img/';
my %m = {} ;
# 取 url 参数
#map{ $m{$1}=$2 if /(.*?)=(.*)/ ; } split /\&/,$r->args ;
# rewrite
# /convert/origin_abc.jpg/format_zyf.png
# /type_img audio video txt bin
# /uid_00000/appid_00000
# /h_000/w_000
map{ $m{$1}=$2 if /(.*?)_(.*)/ ; } split /\//,$r->uri ;
# jpg|jpeg|gif
my $mask = '000'+$m{uid};
$mask = $1 if $mask =~ /.*?(.{3})$/;
my $filename = $1 if $m{origin} =~ /(.*?)\..*/;
if( $m{format} eq "" ){ $m{format}=$1 if $m{origin} =~ /.*?\.(.*)/ }
my $sou_file = "/$m{type}/$mask/$m{uid}/$m{appid}/$m{origin}" ;
# 没有 w h format 走原图
if( $m{h} eq "" and $m{w} eq "" ){
$r->internal_redirect("/img/$sou_file");
return OK ;
}
my $to_file = "/$mask/$m{uid}/$m{appid}/$filename.$m{w}x$m{h}.$m{format}" ;
#处理裁图
#filePath原文件路径
#targetWidth目标尺寸宽
#targetHeight目标尺寸高
#targetFilePath目标文件路径
#返回处理命令字符串
unless (-e "$rpath/$to_file" ){
my $comm = &handleResize( "/$rpath/$sou_file" , $m{w} , $m{h} , "/$rpath/$to_file" ) ;
$client->do_task("shell_run", $comm );
}
$r->internal_redirect("/img/$to_file");
return OK ;
}
#通过调用系统命令identify来确定图片尺寸
#返回宽高数组
sub getImageSize($){
my ($fileName) = @_;
open (IDENTIFY, "identify ".$fileName." |");
my $file_desc = "";
while (my $line = <IDENTIFY>){
$file_desc = $line;
}
close IDENTIFY;
my ($fName,$extandName,$size) = split(/\s/,$file_desc);
my ($width,$height) = split(/x/,$size);
my @result = ();
push(@result,$width);
push(@result,$height);
return @result;
}
#处理裁图
#filePath原文件路径
#targetWidth目标尺寸宽
#targetHeight目标尺寸高
#targetFilePath目标文件路径
#返回处理命令字符串
sub handleResize($$$$){
my ($filePath,$targetWidth,$targetHeight,$targetFilePath) = @_;
my @size = &getImageSize($filePath);
my $width = $size[0]; #原图宽
my $height = $size[1]; #原图高
#比例一致
if( $width/$height == $targetWidth/$targetHeight ){
return "convert ".$filePath." -resize ".$targetWidth."x".$targetHeight." ".$targetFilePath
} else {
#比例不一致时,先缩放到较长的一边,另一边裁剪处理,默认缩小操作
if( $targetWidth>$targetHeight ){
$tempHeight = int( $targetWidth*($height/$width) );
$tempCutHeight = int( ($tempHeight-$targetHeight)/2 ); return "convert ".$filePath." -resize ".$targetWidth."x".$tempHeight." -crop ".$targetWidth."x".$targetHeight."+0+".$tempCutHeight." +repage ".$targetFilePath;
} else {
$tempWidth = int( $targetHeight*($width/$height) );
$tempCutWidth = int( ($tempWidth-$targetWidth)/2 );
return "convert ".$filePath." -resize ".$tempWidth."x".$targetHeight." -crop ".$targetWidth."x".$targetHeight."+".$tempCutWidth."+0 +repage ".$targetFilePath;
}
}
}
1;
__END__
|