Skip to content

Instantly share code, notes, and snippets.

@kkosuge
Created April 12, 2012 14:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kkosuge/2367607 to your computer and use it in GitHub Desktop.
Save kkosuge/2367607 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 / {
if (!-f $request_filename) {
rewrite ^(.*)(.jpg|.JPG|.gif|.GIF|.png|.PNG)$ /scale$1$2 last;
}
}
location /scale {
perl resize::handler;
}
}
}
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 parse_uri{
my $uri = shift;
return unless $uri =~ m{scale/([a-z]\.)?\d+x\d+\.[^/]+.[a-z]+$};
my ($filename) = reverse split("/", $uri);
my $has_option = ($filename =~ m{^[a-z]} ? 1 : 0);
my @splitted_filename = split ('\.', $filename);
my $option = undef;
if ($has_option) {
$option = shift @splitted_filename;
}
my $dimensions = shift @splitted_filename;
my ($width, $height) = split "x", $dimensions;
my $original_filename = join(".", @splitted_filename);
my $ext = pop @splitted_filename;
return +{
option => $option,
width => $width,
height => $height,
ext => $ext,
original_filename => $original_filename,
};
}
sub handler {
my $r = shift;
my $uri=$r->uri;
my $file_info = &parse_uri($uri);
return DECLINED unless $file_info;
my $width = $file_info->{width};
my $height = $file_info->{height};
my $ext = $file_info->{ext};
my $option = $file_info->{option};
my $dest_file="$base_dir/$uri";
my $real_file_path=join("/", $base_dir, $file_info->{original_filename});
return DECLINED if -e $dest_file;
return DECLINED unless -e $real_file_path;
return DECLINED unless $ext =~ /jpe?g|png|gif/;
if ($width > $max_size || $height > $max_size) {
return DECLINED;
}
my $img = Imager->new;
$img->read(file => $real_file_path, type => $ext);
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);
}
return DECLINED;
}
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