I’m trying to trim a variable amount of whitespace in an image only the left and right side using ImageMagick and PHP. Does anyone know how to do this (perhaps using something other than imagemagick?)?
Here’s an example.
I have these two images:


Each has a variable amount of text that is dynamically created in a fixed width image.
What I need to do is trim the background off the right and left side so the images come out like this:


If ImageMagick can’t do it, I am willing to use something else, but I will need help on how exactly because I am not much of a programmer. Thanks!
Here’s my current code that trims all sides of an image:
<?php
/* Create the object and read the image in */
$i = '3';
$im = new Imagick("test".$i.".png");
/* Trim the image. */
$im->trimImage(0);
/* Ouput the image */
//header("Content-Type: image/" . $im->getImageFormat());
//echo $im;
/*** Write the trimmed image to disk ***/
$im->writeImage(dirname(__FILE__) . '/test'.$i.'.png');
/*Display Image*/
echo $img = "<img src=\"test".$i.".png\">";
?>
From what I can see in the ImageMagick docs on cropping and borders, it doesn’t seem to be possible.
you can’t specify an edge for “intelligent” cropping (known as
-trimon the command line), and all the cropping methods that accept a geometry argument need a fixed number for cropping.The only idea that comes to mind is to get the colour of the shaved area in a separate call, run
trimImage, and add the lost areas back using-border.