EmbeddedPerlImageResize

Example module to resize images using image magick
This module will allow us to view images in different sizes. If the image in that size exists, it will be shown. If it does not exist then it will be created.

This code is in production since 01/2008.

You can call an image such as /atifghaffar.jpg (this will return the origional image)

or you can call /atifghaffar.resize_to.XxY.jpg (this will create and return the XxY image, on further requests, it will serve the copy from the disk) for example /atifghaffar.resize_to.100x100.jpg

If you want propotional image, you may leave y=0 for example

/atifghaffar.resize_to.80x0.jpg

Here are some live examples running with the same code. Origional image http://images.worldsoft-cms.info/t/technik-forum.worldsoft.info/profile/1263957/ament.jpg

scaled to 100x100 http://images.worldsoft-cms.info/t/technik-forum.worldsoft.info/profile/1263957/ament.resize_to.100x100.jpg

Scaled to 80 width and propotional height http://images.worldsoft-cms.info/t/technik-forum.worldsoft.info/profile/1263957/ament.resize_to.80x0.jpg

nginx.conf http { perl_modules perl/lib; perl_require resize.pm;

server { location / { root /var/www; if (!-f $request_filename) { rewrite ^(.*)(.jpg|.JPG|.gif|.GIF|.png|.PNG)$ /resize$1$2 last; }    }

location /resize { perl resize::handler; }  } }

perl/lib/resizer.pm package resize; use nginx; use Image::Magick; our $base_dir="/var/www"; our $image;

sub handler { my $r = shift; return DECLINED unless $r->uri =~ m/\.resize_to\.\d{1,}?x\d{1,}?\./; my $uri=$r->uri; $uri=~ s!^/resize!!;

my $dest_file="$base_dir/$uri"; my @path_tokens=split("/", $uri); my $filename=pop @path_tokens; my @filename_tokens=split('\.', $filename);

# We know the last part is the extension; # We know the one before that is the dimensions # We know that the one before that is the resize_to string

my $ext=pop @filename_tokens; my $dimensions=pop @filename_tokens; pop @filename_tokens; $filename=join('.', @filename_tokens, $ext);

my $real_file_path=join("/",  $base_dir, @path_tokens, $filename); return DECLINED unless -f $real_file_path;

my ($width,$height)=split("x", $dimensions); if ($height<1) { $dimensions=$width; }

$image= new Image::Magick; $image->Read($real_file_path); $image->Scale($dimensions); $image->Write($dest_file); $r->sendfile($dest_file); return OK;

}

1; __END__