matthewsnape has asked for the wisdom of the Perl Monks concerning the following question:

I have a directary full of 2 bit gif images. I would like to crop these images to their smallest extents. The best way I could come up with was to itterate through each pixel and store the max and min for x and y and then crop based on those values. This seems a bit clunky, is there a better way?

Replies are listed 'Best First'.
Re: Cropping dependant on image contents
by merlyn (Sage) on May 10, 2005 at 23:07 UTC
      I've used Image::Magick's Trim() method with success before. (though I definitely agree that the PerlMagick docs are not the best).

      My only caveat in using the Trim() method is that my use was when i started with a blank canvas and put stuff in the middle somewhere and wanted it auto-cropped down. In your (OP) case, you may need to tell it what to consider as the background color before calling Trim().
Re: Cropping dependant on image contents
by rduke15 (Beadle) on May 10, 2005 at 23:43 UTC

    I don't see how you could avoid walking through the pixels, but of course, you don't have to examine them all.

    For each of the 4 sides, you only walk the lines inward from the edge, until you bump into the first "color-to-keep" pixel, then you go to the next side.

Re: Cropping dependant on image contents
by Joost (Canon) on May 10, 2005 at 23:12 UTC
Re: Cropping dependant on image contents
by davidrw (Prior) on May 11, 2005 at 13:40 UTC
    Probably best way is one of the above (Image::Magick or gimp), but as mentioned by rduke15, you have to go through pixels, but not all of them. I actualy did this recently, but in a C# program. The code is below if it helps at all as pseudocode. It takes a couple shortcuts in the loop bounds to try to check the minimum number of pixels.