.NET - 围绕调整大小的成像边框
题
我正在尝试在.NET中调整图像大小,但在调整大小的图像周围获得一个微弱的黑色边框。我找到了一个post - http://social.msdn.microsoft.com/forums/en-us/csharpgeneral/thread/cf765094- a1f3-cecdbd07ee15/ 哪个来自某人的人,他表示使目标矩形大于画布工作,但这对我不起作用。它得到了顶部和左边界的riid,但右侧和底部仍然存在,并且是一个完整的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的方式。压缩和质量似乎更好...
其他提示
简单地提供了一种具有想象力实例的拔迹方法,该模拟将WrapMode设置为TileFlipxy。这将防止边缘与背景颜色混合。 for for for for for illy在这里的其他答案中的内存,查看此主旨
对我来说,这是一个糟糕的位图参数。而不是这个:
new Bitmap(width, height, PixelFormat.Format32bppPArgb);
.
只需删除PIXELFORMAT:
new Bitmap(width, height);
.
,一切都是好的。
与Pixelformat在顶部和左边框上有黑色边框。然后我尝试了g.pixeloffsetmode= pixeloffsetmode.highquality;起初似乎很好。但后来我注意到整个图像周围的浅灰色边界。
不隶属于 StackOverflow