.NET – 围绕resize的图像边框

我正在尝试在.NET中调整图像大小,但在resize的图像周围会出现一个模糊的黑色边框。 我发现了一篇posthttp://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/cf765094-c8c1-4991-a1f3-cecdbd07ee15/ ,其中有人说目标矩形大于canvas工作,但这对我不起作用。 它有顶部和左边的边缘,但右边和底部仍然存在,并且是一个完整的1px厚的黑色。

我错过了什么吗? 我的代码如下。

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); } 

试试这样,我想我从未有过黑色边框……

如果要使用System.Drawing库:

 using (var sourceBmp = new Bitmap(sourcePath)) { decimal aspect = (decimal)sourceBmp.Width / (decimal)sourceBmp.Height; int newHeight = (int)(newWidth / aspect); using (var destinationBmp = new Bitmap(newWidth, newHeight)) { using (var destinationGfx = Graphics.FromImage(destinationBmp)) { destinationGfx.InterpolationMode = InterpolationMode.HighQualityBicubic; destinationGfx.DrawImage(sourceBmp, new Rectangle(0, 0, destinationBmp.Width, destinationBmp.Height)); destinationBmp.Save(destinationPath, ImageFormat.Jpeg); } } } 

或者你可以用wpf做同样的事情,像这样:

 using (var output = new FileStream(outputPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None)) { var imageDecoder = BitmapDecoder.Create(inputStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None); var imageFrame = imageDecoder.Frames[0]; decimal aspect = (decimal)imageFrame.Width / (decimal)imageFrame.Height; var height = (int)(newWidth / aspect); var imageResized = new TransformedBitmap(imageFrame,new ScaleTransform( newWidth / imageFrame.Width * Dpi / imageFrame.DpiX, height / imageFrame.Height * Dpi / imageFrame.DpiY, 0, 0)); var targetFrame = BitmapFrame.Create(imageResized); var targetEncoder = new JpegBitmapEncoder(); targetEncoder.Frames.Add(targetFrame); targetEncoder.QualityLevel = 80; targetEncoder.Save(output); } 

我推荐WPF方式。 压缩和质量似乎更好……

只需为DrawImage方法提供一个ImageAttributes实例,该实例将WrapMode设置为TileFlipXY。 这将防止边缘与背景颜色混合。

对于不像其他答案那样泄漏内存的示例代码, 请参阅此要点

对我来说这是一个糟糕的Bitmap参数。 而不是这个:

 new Bitmap(width, height, PixelFormat.Format32bppPArgb); 

只需删除PixelFormat:

 new Bitmap(width, height); 

一切都很好。

使用PixelFormat,我在顶部和左边框上都有黑色边框。 然后我尝试了g.PixelOffsetMode = PixelOffsetMode.HighQuality; 起初看起来很好。 但后来我发现整个图像周围都是浅灰色边框。