Skip to content

Instantly share code, notes, and snippets.

@Shinpeim
Forked from kkosuge/Imager
Created April 13, 2012 03:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shinpeim/2373382 to your computer and use it in GitHub Desktop.
Save Shinpeim/2373382 to your computer and use it in GitHub Desktop.
perl -MImager -e 'print join "\n", sort keys %Imager::formats'
./configure --with-http_perl_module
make
sudo make install
sudo apt-get install libjpeg-dev libtiff-dev libpng-dev giflib-dev libttf-dev libfreetype6-dev
sudo cpan -i Imager
http {
perl_modules perl/lib;
perl_require resizer.pm;
server {
listen 80;
server_name pic.kksg.net;
root /var/www/pic;
location /scale {
if (-f $request_filename) { break; }
perl resize::handler;
}
location / {
if (-f $request_filename) { break; }
}
}
}
package resize;
use strict;
use warnings;
use nginx;
use Imager;
our $base_dir = "/var/www/pic";
our $max_size = 3000;
# example URL
# http://example.com/scale/128x128.sushi.png
# http://example.com/scale/c.600x150.sushi.png
sub handler {
my $r = shift;
my $uri=$r->uri;
return DECLINED unless ($uri =~ m/\d{1,}?x\d{1,}?\./);
my $dest_file="$base_dir/$uri";
my @path_tokens=split("/", $uri);
my $filename=pop @path_tokens;
my @filename_tokens=split('\.', $filename);
my $ext=pop @filename_tokens;
pop @filename_tokens;
my $dimensions = pop @filename_tokens;
my $option = pop @filename_tokens;
$filename=~s/\w{1,}?\.?\d{1,}?x\d{1,}?\.//;
my $real_file_path=join("/", $base_dir, $filename);
my ($width,$height)=split("x", $dimensions);
return DECLINED unless $ext =~ /jpe?g|png|gif/;
return DECLINED unless -f $real_file_path;
if (-e $dest_file) {
$r->sendfile($dest_file);
return OK;
}
if ($width > $max_size || $height > $max_size) {
return DECLINED;
}
my $img = Imager->new;
$img->read(file => $real_file_path);
if ($option eq "c"){
$img->scale(xpixels => $width, ypixels => $height, qtype=>'mixing')->crop(width => $width, height => $height)->write(file => $dest_file);
} else{
$img->scale(xpixels => $width, ypixels => $height, qtype=>'mixing')->write(file => $dest_file);
}
$r->sendfile($dest_file);
return OK;
}
1;
__END__
sudo apt-get install gcc libpcre3 libpcre3-dev libssl-dev libperl-dev
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment