Perl

Fetching Image details in Perl

Image::Size is fine, if size is the only thing, which matters. Sometimes, however, it isn’t enough, and when that is the case Image::Info (again fetched from CPAN) is your friend. Point it to a file (through various methods), and it will return a hash with all the information available about the image you pointed at. Most popular formats are supported.

#!/usr/bin/perl -w
use strict;
use Image::Info;

# Just fetch the size
my $imgInfo = Image::Info::image\_info("test.jpg");

# Print out all info fetched from the image
for (keys %$imgInfo) { print " $\_ -> $imgInfo->{$\_}n"; }

exit();

Rotating an Image with Perl

Turning images is quite simple. In the example below an image is turned 90 degrees clockwise, wirtten to a file, turned another 90 degress and written to a file again.

#!/usr/bin/perl -w
use strict;
use Image::Magick;

my $image = Image::Magick->new(magick=>'JPEG');
my $x = $image->Read('test.jpg');

$x = $image->Rotate(degrees=>90); # 90 degress clockwise
$x = $image->Write('test.90.jpg');

$x = $image->Rotate(degrees=>90); # Another 90 degress clockwise
$x = $image->Write('test.180.jpg');

exit();

IP address conversion with Perl

With Perl you can do many interesting transformations of IP-numbers. Below is two small examples allowing conversions from “IP quad” (xxx.xxx.xxx.xxx) format to a single decimal and back. The decimal format may be more convenient and efficient to store in a database.

  sub ip2dec ($) {
    return unpack N => pack CCCC => split /\\./ => shift;
  }

  sub dec2ip ($) {
    return join '.' => map { ($\_\[0\] >> 8\*(3-$\_)) % 256 } 0 .. 3;
  }

In CPAN you can find many modules aimed at using and manipulating IP-addressees.

Bulk resizing images with Perl

Suppose you’ve just filled you digital camera with an endless stream of photos. You want to place them online at your website, but placing 5+ megapixel files online, well…probably a bad idea. Let’s resize them to a propper size - and why not use Perl and ImageMagick for the job.  Not a problem, here’s a complete example on how to resize all images in a directory . Make sure you have ImageMagick installed.

Converting between image formats with Perl

Changing files from one format to another is quite easy with a little bit of ImageMagick . In the example below a JPG image (test.jpg) is converted into a GIF-image (test.gif). To output in a different (ImageMagick supported ) format, just change the “image->Set” line.

#!/usr/bin/perl -w use strict; use Image::Magick;
my $image = Image::Magick->new();

# To explicitly set image format use this instead: 
# my $image = Image::Magick->new(magick=> 'JPEG');
my $x = $image->Read('test.jpg'); 
$x = $image->Set(magick => 'GIF'); $x = $image->Write('test.gif');
exit();