c# - 图像大小调整 - 有时质量很差?

标签 c# image resize image-scaling

我正在调整一些图像的大小以适应用户的屏幕分辨率;如果宽高比错误,则应裁剪图像。 我的代码如下所示:

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

示例调整大小的图像: alt text

注意:我有一个 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/

相关文章:

c# - 有谁知道 AsyncPageable 是什么?

Java ImageIO.read 导致 OSX 挂起

excel - 在 VBA 中精确调整图表的大小

c# - 如何在ce中创建空数据库并用datagridview显示

c# - 将 byte[] 数组的一部分复制到 PDFReader

java - 如何从 JButton/JLabel 更新 ImageIcon

python - 如何使用 wand python 删除图像元数据

javascript - 在页面调整大小时更改 CSS

C# 判断表单是否最大化

c# - Monotouch Crashdump 缺少对我的代码的任何引用