Is there a 'trim' function like in Photoshop in .net GDI?
Most Photoshop people would know what this does, basically it re-sizes the image removing all empty space.
Is there a function in GDI+ that does something similar? Or do I h开发者_高级运维ave to write my own? Or if somebody has one already that would be nice.
No, there is not one out-of-the-box, you would have to write your own, determining what "empty" space is, and then adjusting (or copying) the image to remove that "empty" space.
Actually, writing this wouldn't be too terribly difficult. Being that I use Photoshop daily to design websites, and my application graphics for my own software I develop, Trim bases it off of a pixel color you select. You could do the calculation in four rectangular passes by navigating through the rows of pixels comparing their color to the color you wish to trim, storing the cordinates you are at along the way. Let me explain.
Essentially what you are doing is navigating through the pixels from left to right, top to bottom, generating a Rectangle object that stores the region of (in this case) White pixels. This would be done in four passes, so you would have generated four Rectangle regions you would clip from the image.
The logic behind the calculation is as follows (in semi-psuedo code C#)
int x = 0, y = 0;
Rectangle rect = new Rectangle();
bool nonWhitePixelFound = false;
for (int row = 0; row < image.Bounds.Height; row++) {
if (!nonWhitePixelFound) {
for (int column = 0; column = image.Bounds.Width; column++) {
if (pixel.getColor() != Color.White) {
rect.Width++;
}
else {
rightBoundPixelFound = true; // Okay, we encountered a non-white pixel
// so we know we cannot trim anymore to the right
rect.Height--; // Since we don't want to clip the row with the non-white pixel
nonWhitePixelFound = true;
return rect; // I did not wrap this code in a function body in this example,
// but to break both loops you should return, or this would be
// a rare case to use goto
}
}
}
rect.Height++; // Since we have not found a non-white pixel yet, and went through the
// entire row if pixels, we can go ahead and check the next row
}
You would essentially repeat this algorithm for 4 passes (4 sides of the image), until you have trimmed all the whitespace (or whatever color you need). This should work for non-traditional shaped images with scattered colors as well because of the algorithm. It stops calculating the region as soon as it detects a non-white pixel, and you should then clip that region, and perform another pass. Rinse and repeat.
Note that I have not tested this; it is all in theory, but I wanted to provide you a general idea or approach to this other then just linking to a 3rd Party Library or component.
Edit:
- Here is a link that provides a similar approach with an actual code sample.
- Automatically trim a bitmap to minimum size?
There is nothing built into GDI+, but you can use the AForge.NET Library, which does do that and more.
精彩评论