19

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:
Test
Test Again
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:
TestResult
Test Again Result

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\">";
?>
0

6 Answers 6

21

I think you are on the right track with ImageMagick's -trim operator 1), but the trick would be to get it tell you what it would do without actually doing it, and then modify that to do what you really want...

So, to get the trim-box ImageMagick calculates for your first image, you do this:

convert -fuzz 10% image.jpg -format "%@" info:
60x29+21+31

That is a 60x29 pixel rectangle, offset 21 across and 31 down from the top left corner. Now, we want to get these values into bash variables, so I set the IFS (Input Field Separator) to split fields on spaces, x and also + signs:

#!/bin/bash
IFS=" x+" read a b c d < <(convert -fuzz 10% image.jpg -format "%@" info:)

echo $a $b $c $d
60 29 21 31

Now I can ignore the 29 and the 31 because we are only interested in cropping the width, and crop like this:

convert image.jpg -crop "${a}x+${c}+0" out.jpg

So, for your 2 images, I get these:

enter image description here enter image description here

and the full procedure is this:

#!/bin/bash
IFS=" x+" read a b c d < <(convert -fuzz 10% image.jpg -format "%@" info:)
convert image.jpg -crop "${a}x+${c}+0" out.jpg

Notes

1) The -format %@ is just a shorthand for the -trim operator, which would be this in full

convert image.jpg -trim info:
image.jpg JPEG 72x40 200x100+16+24 8-bit sRGB 0.000u 0:00.000
1
  • 1
    Brilliant explanation and answer. Works smooth as silk. Thank you so much.
    – Oleg Popov
    Mar 4, 2015 at 8:36
7
+50

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-trim on 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.

Edit: The IM manual is suggesting something similar. Check out Trimming Just One Side of an Image. I'm not familiar with IM's PHP extension to translate the code into PHP calls but it should be half-way straightforward.

3
  • 4
    I was able to trim the right and left side of an image using this code: exec('convert test4.png -gravity West -background white -splice 5x0 -background black -splice 5x0 -trim +repage -chop 5x0 test44.png'); Thank you! exec('convert test44.png -gravity East -background white -splice 1x0 -background black -splice 1x0 -trim +repage -chop 1x0 test44.png');
    – Nathan
    Nov 4, 2011 at 6:34
  • 1
    You can also combine trimming sides into one command (which is more efficient and will provide better quality), e.g., for right and bottom margins: convert -gravity North -background white -splice 0x1 -trim +repage -chop 0x1 -gravity West -background white -splice 1x0 -trim +repage -chop 1x0 <input> <output>
    – dvo
    May 16, 2016 at 16:02
  • the above command adds a white line down the middle of the image? :(
    – 00-BBB
    Jan 9, 2020 at 11:33
5

The GD based library WideImage has something similar. It's called autoCrop, by default it works on all four sides.

However, you could just add another parameter and based on it only crop top/bottom or left/right.

autoCrop code

It's pretty well documented. $img is a WideImage_Image type. There is also an interactive online demo of it.

Related question: Removing black bars off video thumbnail.

2
  • 1
    As an additional comment: You can use that library and cut off all sides, then use the same library to center the cropped image onto a another picture that has the right height (and same width as the cropped image) with the background color in question. Job done (if the text was originally centered on y-axis).
    – hakre
    Nov 1, 2011 at 15:46
  • This looks like it will work (I have WideImage up and running) - but I am not sure how to add another parameter to only autocrop the left and right sides of an image. Could you supply code? Thanks for your help.
    – Nathan
    Nov 4, 2011 at 5:28
2

Using GD:

function imageautocrop( &$img) {
    $emptycol = function ( $img, $x, $min, $max) {
        for( $y=$min; $y<$max; $y++) {
            $col = imagecolorsforindex( $img, imagecolorat( $img, $x, $y));
            if( $col['alpha'] != 127) return false;
        }
        return true;
    }
    $trim = Array('top'=>0,'bot'=>0,'lft'=>0,'rgt'=>0);
    $size = Array('x'=>imagesx($img)-1,'y'=>imagesy($img)-1);
    // code for affecting rows removed due to question asked
    while( $emptycol( $img, $trim['lft'], $trim['top'], $size['y']-$trim['bot'])) $trim['lft']++;
    while( $emptycol( $img, $size['x']-$trim['rgt'], $trim['top'], $size['y']-$trim['bot'])) $trim['rgt']++;
    $newimg = imagecreate( $size['x']-$trim['lft']-$trim['rgt']+1, $size['y']-$trim['top']-$trim['bot']+1);
    imagecopy( $newimg, $img, 0, 0, $trim['lft'], $trim['top'], imagesx($newimg)+1, imagesy($newimg)+1);
    imagedestroy($img);
    $img = $newimg;
}

It's very old code of mine, so probably not optimal, but it does the job.

2
  • I've tried to use your code, but I can't get it to work...like I said I am not much of a programmer. Could you give me lines to load an image and then write changes to the image? Sorry for my ignorance.
    – Nathan
    Nov 4, 2011 at 5:35
  • $img = imagecreatefrompng("FILENAME.png"); imageautocrop($img); imagepng($img,"NEWFILENAME.png"); Nov 4, 2011 at 6:27
0

It is a two step process as text is dynamically generated

  • Generate the text image, determine width(image)
  • Overlay text image into background, determine width(background)
  • Use one tool mentioned above, crop (width(background)-width(image)/2 on either side

The trick is figuring out the width(image). See: How can I auto adjust the width of a GD-generated image to fit the text?

Then again, if you know width(image), you can crop the width(background) first before overlay

-2

Use cropImage() instead. Something like this, perhaps:

$img_x_size = 800;    // Set these to relevant values
$img_y_size = 600;

$crop_pixels = 20;    // How many pixels to crop

// cropImage(XsizeOfCrop, YsizeOfCrop, CropXPos, CropYPos)
$im->cropImage($img_x_size - $crop_pixels, $img_y_size, 0, $crop_pixels / 2);
1
  • 1
    The problem with this (if I am understanding crop_pixels correctly) is that it only removes a fixed amount of pixels - trimImage actually crops the image until it comes up against something other than the background color (so as to make the image as small as possible). So I don't think this will work....I added clarity to my question since it was a little confusing. Thanks!
    – Nathan
    Oct 21, 2011 at 22:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.