Dynamic Images with ImageMagick

From Dev411: The Code Wiki

Sometimes you may want to create a dynamic image and deliver it via HTTP. To do this you can use ImageMagick to read in the image and then send it to STDOUT after sending the proper HTTP header content-type as shown in the short Perl CGI script below:

  #!/usr/local/bin/perl
  use strict; use warnings;
  use CGI;
  use Image::Magick;

  my $q = CGI->new;
  print $q->header( -type=>'image/png' );

  my $img = Image::Magick->new;
  $img->ReadImage( '/path/to/imagefile.png' );
  binmode STDOUT;
  $img->Write( 'png:-' );

If you want to file to be downloaded with a specific file name instead of viewed, you can use the following instead of printing a header content-type:

 print "Content-Disposition: attachment; filename = $filename\n\n";