每当您调整图像大小时,都会有一些质量损失 - 没有办法解决这个问题,但您可以通过在图形上下文中使用最高质量选项来帮助将其最小化。
这是我使用普通 GDI+ 函数时使用的:
public static Bitmap ResizeImage(Bitmap bmp, int width, int height,
InterpolationMode mode = InterpolationMode.HighQualityBicubic)
{
Bitmap bmpOut = null;
try
{
decimal ratio;
int newWidth = 0;
int newHeight = 0;
// If the image is smaller than a thumbnail just return original size
if (bmp.Width < width && bmp.Height < height)
{
newWidth = bmp.Width;
newHeight = bmp.Height;
}
else
{
if (bmp.Width == bmp.Height)
{
if (height > width)
{
newHeight = height;
newWidth = height;
}
else
{
newHeight = width;
newWidth = width;
}
}
else if (bmp.Width >= bmp.Height)
{
ratio = (decimal) width/bmp.Width;
newWidth = width;
decimal lnTemp = bmp.Height*ratio;
newHeight = (int) lnTemp;
}
else
{
ratio = (decimal) height/bmp.Height;
newHeight = height;
decimal lnTemp = bmp.Width*ratio;
newWidth = (int) lnTemp;
}
}
//bmpOut = new Bitmap(bmp, new Size( newWidth, newHeight));
bmpOut = new Bitmap(newWidth, newHeight);
bmpOut.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);
Graphics g = Graphics.FromImage(bmpOut);
g.InterpolationMode = mode;
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.FillRectangle(Brushes.White, 0, 0, newWidth, newHeight);
g.DrawImage(bmp, 0, 0, newWidth, newHeight);
}
catch
{
return null;
}
return bmpOut;
}
这会将图像的大小调整为宽度或高度中的最大值 - 您可以更改该算法以满足调整大小的需要。
如果你想处理文件,你可以添加另一个包装上面代码的助手:
public static bool ResizeImage(string filename, string outputFilename,
int width, int height,
InterpolationMode mode = InterpolationMode.HighQualityBicubic)
{
using (var bmpOut = ResizeImage(filename, width, height, mode) )
{
var imageFormat = GetImageFormatFromFilename(filename);
if (imageFormat == ImageFormat.Emf)
imageFormat = bmpOut.RawFormat;
bmpOut.Save(outputFilename, imageFormat);
}
return true;
}
GDI+ 通常不是高质量图像处理的最佳解决方案 - 它很不错,但如果您需要 Web 应用程序中的最高质量、更好的性能和线程安全,则需要考虑其他选项。
Bertrand LeRoy 前段时间发表了一篇关于图像调整大小的精彩文章,其中提供了一些使用核心 .NET 框架的替代方案。 http://weblogs.asp.net/bleroy/state-of-net-image-resizing-how-does-imageresizer-do