Page Discussion History


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


Here are some live examples running with the same code.

Origional image

scaled to 100x100

Scaled to 80 width and propotional height


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; 


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) {
  $image= new Image::Magick;
  return OK;