Voodoo Magic with GDI+

Cropping images sounds easy, you get an image, you tell it what size you want it, issue the bitmap.Crop() command and it crops.

No it doesn't. It crops and gives you a little freebie...random lines on your images.

So how do you resolve it? well its as simple as 3 easy steps (wrapped in some GDI+ black magic).

  1. Create your final bitmap at the correct size.
  2. Create your source bitmap from the source image.
  3. Create a temporary rectangle with dimensions 2px bigger than the final one.

Step 1 is nice and simple - create your bitmap as you would want it to appear (say 150px x 150px). Nothing difficult there.

Bitmap bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);

Step 2 is also nice and easy

System.Drawing.Image imgPhoto = CreateImageFromUrl(sourcePath);

Step 3 Crop your image - heres the science bit...

grPhoto.DrawImage(imgPhoto,
new Rectangle(-2, -2, destWidth + 2, destHeight + 2),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);


Why does it work? imgPhoto is the image you are using. The first new rectangle is declared as being 1px larger than the imgPhoto in all dimensions and starts 1px to the left and 1px further up than your cropped image, and the second rectangle is the rectangle the same size as your source so that GDI knows how to scale the images.

The code doesn't so much as remove them from your crop as leaves them in but makes them outside the bounds of your final image, by doing so, when you do save the image GDI+ ignores them and they aren't displayed.

I'll try and get a full working example on here for now but that should give you enough information to remove any weird lines you are seeing on your cropped images.

No comments:

Note: only a member of this blog may post a comment.

Powered by Blogger.