我正在调整一些图像的大小以适应用户的屏幕分辨率;如果宽高比错误,则应裁剪图像。 我的代码如下所示:
protected void ConvertToBitmap(string filename)
{
var origImg = System.Drawing.Image.FromFile(filename);
var widthDivisor = (double)origImg.Width / (double)System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;
var heightDivisor = (double)origImg.Height / (double)System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;
int newWidth, newHeight;
if (widthDivisor < heightDivisor)
{
newWidth = (int)((double)origImg.Width / widthDivisor);
newHeight = (int)((double)origImg.Height / widthDivisor);
}
else
{
newWidth = (int)((double)origImg.Width / heightDivisor);
newHeight = (int)((double)origImg.Height / heightDivisor);
}
var newImg = origImg.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
newImg.Save(this.GetBitmapPath(filename), System.Drawing.Imaging.ImageFormat.Bmp);
}
在大多数情况下,这工作正常。但对于某些图像,结果的质量极差。看起来会被调整到非常小的尺寸(缩略图大小)并再次放大。但是图像的分辨率是正确的。我能做什么?
示例原始图像: alt text http://img523.imageshack.us/img523/1430/naturaerowoods.jpg
注意:我有一个 WPF 应用程序,但我使用 WinForms 函数来调整大小,因为它更容易,而且我已经需要对 System.Windows.Forms 的引用以获取托盘图标。
最佳答案
将方法的最后两行更改为:
var newImg = new Bitmap(newWidth, newHeight);
Graphics g = Graphics.FromImage(newImg);
g.DrawImage(origImg, new Rectangle(0,0,newWidth,newHeight));
newImg.Save(this.GetBitmapPath(filename), System.Drawing.Imaging.ImageFormat.Bmp);
g.Dispose();
关于c# - 图像大小调整 - 有时质量很差?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/803987/