January 25, 2004

Rotating an image with Image::Magick and Perl

While messing with photos, I needed a simple way to rotate an image that didn't involve loading up Gimp or Paint Shop, or whatever. Here it is.

What I don't get is that it segfaults every time I run it. However, the image is always created correctly. Any tips would be welcome. Meanwhile, I'm rotating images with less pain.

Usage: rotateimage img deg where img is the path to the image, and deg is the number of degrees through which you want to rotate it, with the default being 90 counterclockwise.

#!/usr/bin/perl
use Image::Magick;
my $image = Image::Magick->new;
my $deg = $ARGV[1] || 90;

print "Reading $ARGV[0]\n";
open (IMAGE, $ARGV[0]);
$image->Read(file=>\*IMAGE);
close(IMAGE);

$image->Rotate($deg);
$filename = $ARGV[0];
$filename =~ s/(.*)\.(.*)$/$1.new.$2/;
print "Writing $filename\n";
open(IMAGE, ">$filename");
$image->Write(file=>\*IMAGE, $filename=>$filename);
close(IMAGE);
Posted by rbowen at January 25, 2004 11:33 AM | TrackBack
Comments

You can do lossless rotation of jpeg files too - use a utility like jpegtran (comes in libjpeg rpm on Fedora and no doubt other Linux distributions).

Posted by: Mark Cox on January 26, 2004 07:03 AM
Post a comment