c# - 在 C# 中以编程方式调整图像大小

标签 c# .net winforms image-manipulation

<分区>

Possible Duplicate:
Resize an Image C#

如何在 C# 中以编程方式调整图像大小,使其适合 winforms 控件?

最佳答案

将图像缩放到 PictureBox 中:

class ImageHandling
{
    public static Rectangle GetScaledRectangle(Image img, Rectangle thumbRect)
    {
        if (img.Width < thumbRect.Width && img.Height < thumbRect.Height)
            return new Rectangle(thumbRect.X + ((thumbRect.Width - img.Width) / 2), thumbRect.Y + ((thumbRect.Height - img.Height) / 2), img.Width, img.Height);

        int sourceWidth = img.Width;
        int sourceHeight = img.Height;

        float nPercent = 0;
        float nPercentW = 0;
        float nPercentH = 0;

        nPercentW = ((float)thumbRect.Width / (float)sourceWidth);
        nPercentH = ((float)thumbRect.Height / (float)sourceHeight);

        if (nPercentH < nPercentW)
            nPercent = nPercentH;
        else
            nPercent = nPercentW;

        int destWidth = (int)(sourceWidth * nPercent);
        int destHeight = (int)(sourceHeight * nPercent);

        if (destWidth.Equals(0))
            destWidth = 1;
        if (destHeight.Equals(0))
            destHeight = 1;

        Rectangle retRect = new Rectangle(thumbRect.X, thumbRect.Y, destWidth, destHeight);

        if (retRect.Height < thumbRect.Height)
            retRect.Y = retRect.Y + Convert.ToInt32(((float)thumbRect.Height - (float)retRect.Height) / (float)2);

        if (retRect.Width < thumbRect.Width)
            retRect.X = retRect.X + Convert.ToInt32(((float)thumbRect.Width - (float)retRect.Width) / (float)2);

        return retRect;
    }

    public static Image GetResizedImage(Image img, Rectangle rect)
    {
        Bitmap b = new Bitmap(rect.Width, rect.Height);
        Graphics g = Graphics.FromImage((Image)b);
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.DrawImage(img, 0, 0, rect.Width, rect.Height);
        g.Dispose();

        try
        {
            return (Image)b.Clone();
        }
        finally
        {
            b.Dispose();
            b = null;
            g = null;
        }
    }
}

以及如何使用它:

Image img = Image.FromFile(imageFilePath);
Rectangle newRect = GetScaledRectangle(img, pictureBox1.ClientRectangle);
pictureBox1.Image = ImageHandling.GetResizedImage(img, newRect);

关于c# - 在 C# 中以编程方式调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2191139/

相关文章:

C# Windows 窗体 : Using List<KeyValuePair> to create a Top 10 Leaderboard

c# - 从 C# 代码中删除 dataGridView1_CellContentClick() 会导致构建失败 - 为什么?

c# - Control.Enabled 是如何工作的?

c# - 确定派生自哪个泛型类型对象

c# - 从 App.config 文件中定义的连接字符串获取服务器名称?

c# - 如何使用 SqlParameter.Offset 属性和 ADO.NET 在 SQL Server 2012 中存储二进制文件

c# - Vlc.DotNet NextFrame

c# - 使用 Selenium 获取输入字段的当前文本

c# - 当 MessageBox 打开时(或 "closing"),防止父表单接收 KeyUp 事件

c# - 与 Outlook 互操作的 OpenSharedItem 在 Office 2003 中抛出奇怪的异常,与 Office 2008 一起工作