This project has moved. For the latest updates, please go here.

Crop/Trim White space around an image

Feb 27, 2015 at 9:54 AM
Edited Feb 27, 2015 at 9:56 AM
Hi,

I would like to crop the white space around an image. Below is the code I'm using. But it doesn't works. Am I missing anything?
using (MagickImage image = new MagickImage(@"D:\image\input.jpg"))
            {                
                image.Trim();                
                image.Write(@"D:\out.jpg");
            }
Below is the image I'm trying to trim.
Image

Screenshot: http://screencast.com/t/NmQ7321tq7yp
Coordinator
Feb 27, 2015 at 11:01 AM
The problem is that you are reading a jpeg files as your input. Jpg is lossy so your 'white' pixels are not fully white. You can fix this by setting a ColorFuzz percentage. You might have to tweak the percentage for your situation but your input file converts properly when I used 10%:
using (MagickImage image = new MagickImage(@"D:\image\input.jpg"))
{
  image.ColorFuzz = new Percentage(10);
  image.Trim();
  image.Write(@"D:\out.jpg");
}
Feb 27, 2015 at 5:25 PM
Thank you very much! This works great! But I have a question on setting ColorFuzz. What does this actually do? How does the percentage setting work? As I have to deal with lot of images, I just want to understand what that setting mean.
Coordinator
Feb 27, 2015 at 8:42 PM
Edited Feb 28, 2015 at 8:30 AM
You can find a good explanation in the documentation of ImageMagick here: http://www.imagemagick.org/Usage/color_basics/#fuzz
Mar 2, 2015 at 5:56 PM
Thank you! This is very interesting :)

I would also like to find whether an image has borders around it or not. Is that possible?

Thank you!
Coordinator
Mar 2, 2015 at 6:14 PM
It really depends on what you consider a border. If you can define what you consider a border then you could probably detect it with some code. This won't be easy if what you consider a border sometimes is part of the image.
Mar 2, 2015 at 6:24 PM
Thank you very much for your response!