2010-06-08

how to retrieve image size in perl

today's topic is quite easy: retrieving image size (in perl, with the help of cpan of course). indeed, when one wants to resize an image, it's often interesting to know its current size.

the easiest way to retrieve those information is of course to use image::size:

easy, wasn't it?

however, as mentioned previously, retrieving those information is often just the prelude before doing some transformation to the image itself. and image::size, while doing it perfectly, does only one thing - it cannot be used for any other image manipulation. so if you intend to use another module after, you can as well use this other module to retrieve this information: that'll be faster (image read only once) and use less memory (only one module loaded). here's how to get those information with image::magick:

it wasn't that difficult, and opens the whole image magick world to your program!

6 comments:

  1. just another way ( from http://search.cpan.org/~tonyc/Imager-0.74/lib/Imager/ImageTypes.pod#Image_Attribute_functions )

    use Imager;

    if (my $img = Imager->new(file=>'/path/to/image.png')) {
    my ($w, $h) = ($ing->getwidth, $img->getheight);
    }

    ReplyDelete
  2. and another: http://search.cpan.org/dist/Image-Imlib2/

    use Image::Imlib2;
    my $image = $image = Image::Imlib2->load("foo.png");
    my $width = $image->width;
    my $height = $image->height;

    I tend to use Image::Imlib2 over Image::Magick these days - just feels a bit faster and cleaner

    ReplyDelete
  3. @ranguard: the problem with imlib2 being that you are forced to write the result to a file before using it (in tk, for example), instead of getting the result image in a blob of data.

    ReplyDelete
  4. I have a ubuntu 10.4 and either the Imagemagick 6.6.4-10 installed with apt and the one installed from surce give the same error:

    >
    Can't locate Image/Magick.pm in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.10.1 /usr/local/share/perl/5.10.1 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.10 /usr/share/perl/5.10 /usr/local/lib/site_perl .) at ./pro.cgi line 2.
    BEGIN failed--compilation aborted at ./pro.cgi line 2.
    <
    I did googled a lot but can't find solutions.
    it's frustrating. The same error whe I use Image Size.

    ReplyDelete
  5. @sebastiano: then image magick bindings for perl aren't installed. i'm not running ubuntu, but i guess you need to install the package libimage-magick-perl (or sthg like that).
    or you can install it manually with a cpan client.

    ReplyDelete
  6. search for "perlmagick" in Synaptic Package Manager or aptget install perlmagick

    ReplyDelete