views:

444

answers:

1

I have a few JPG Images. Some of them may have a black border on one or more sides, and I'd like to remove them. The black border may not go around the actual image - some may only have the border at the bottom (with the actual image at the top), while some could be centered (which means black borders on two sides, but not connected). Worse, the images are JPG Compressed, so they may not be exactly 0,0,0 black anymore.

In a Paint Program, I would "simply" use the Magic Wand tool with a low tolerance, but I need to do it in C# on ASP.net, and I don't know what the best way of doing this is.

Should I "scan" each line and then each column (two nested for-loops) to find black areas? Sounds somewhat stupid to do, performance and CPU-Load-wise. Or does GDI+ have some magic wand tool build in already?

The images are not that big (474x474 pixels maximum) and cached afterwards, but I need to keep the server load as low as possible.

Any hints what the least stupid way of doing it would be?

+2  A: 

It seems like for each edge you could do something like this:

for each edge:
    for (i = 0; ; i++) {
         compute average pixel value along edge row/column + i
         if (average value > threshold)
              break;
    }
    crop image
Eric
That approach seems a bit brute-force (two for-loops), but it is surprisingly fast (less than 1 millisecond per picture). Thanks for the idea with the Average Color value.
Michael Stum
The sad truth with image processing is, at least at a lower level, you have to iterate over all pixels of interest. Also, be a bit careful with this method if users can upload mostly black images. Maybe set an upper limit on the allowed border size.
Eric