How To: Fix Random Borders in GDI+

Posted Saturday December 8, 2012 at 12:20:58 pm in Development

In certain cases, images that are generated by your typical resize/crop methods in the .NET world (it's usually the same code snippet that has been recycled across the internet over the last 10 years, it seems) could have a "ghost" border around the edges of the image.

Libor Tinka actually mentions a reason for this here:

This "phenomenom" is called ringing, for those curious. This occurs because of the algorithm is averaging detail from the surrounding pixels just along the edge of the image. This is actually implemented in some sharpening algorithms out there.

The fix for this situation is actually applying an ImageAttributes class with the Wrap Mode set to TileFlipXY when calling the DrawImage method on your image:


using (ImageAttributes wrapMode = new ImageAttributes())
    g.DrawImage(input, rect, 0, 0, input.Width, input.Height, GraphicsUnit.Pixel, wrapMode);


Also, it's a perfect time to remind developers to utilize the using statement in C# whenever possible. 

The opinions expressed herein are my own personal opinions and do not represent my employer’s view