Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET - Border around resized imaged

I'm trying to resize an image in .NET, but get a faint black border around the resized image. I found a post - http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/cf765094-c8c1-4991-a1f3-cecdbd07ee15/ which from someone who said making the destination rectangle larger than the canvas worked, but this doesn't work for me. It gets riid of the top and left borders, but the right and bottom are still there, and are a full 1px thick black.

Am I missing something? My code is below.

Image image = ... // this is a valid image loaded from the source
Rectangle srcRectangle = new Rectangle(0,0,width, height);
        Size croppedFullSize = new Size(width+3,height+3);
        Rectangle destRect = new Rectangle(new Point(-1,-1), croppedFullSize);
        using(Bitmap newImage = new Bitmap(croppedFullSize.Width, croppedFullSize.Height, format))
        using(Graphics Canvas = Graphics.FromImage(newImage)) {
            Canvas.SmoothingMode = SmoothingMode.AntiAlias;
            Canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
            Canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
            Canvas.FillRectangle(Brushes.Transparent, destRect);
            Canvas.DrawImage(image, destRect, srcRectangle, GraphicsUnit.Pixel);


            newImage.Save(filename, image.RawFormat);
        }
like image 783
Echilon Avatar asked Mar 27 '11 21:03

Echilon


1 Answers

Simply provide the DrawImage method with an ImageAttributes instance which has WrapMode set to TileFlipXY. This will prevent the edge from blending against the background color.

For sample code that doesn't leak memory like the other answers here, see this gist

like image 195
Lilith River Avatar answered Oct 27 '22 20:10

Lilith River