返回

c# .net framework 改变图片尺寸

2023-11-05 c# .net .net framework c#改变图片尺寸 849 0

在 C# .NET Framework 中,可以使用以下方法来改变图片尺寸:

使用 Image.Resize() 方法

要在C#中使用.NET Framework来改变图像的尺寸,你可以使用System.Drawing命名空间提供的类。以下是一个简单的示例,展示如何将图像调整为指定的宽度和高度:

using System;
using System.Drawing;

class Program
{
    static void Main()
    {
        string inputImagePath = "input.jpg"; // 输入图像路径
        string outputImagePath = "output.jpg"; // 输出图像路径
        int newWidth = 800; // 新宽度
        int newHeight = 600; // 新高度

        ResizeImage(inputImagePath, outputImagePath, newWidth, newHeight);
    }

    static void ResizeImage(string inputImagePath, string outputImagePath, int newWidth, int newHeight)
    {
        using (var originalImage = Image.FromFile(inputImagePath))
        {
            using (var resizedImage = new Bitmap(newWidth, newHeight))
            {
                using (var graphics = Graphics.FromImage(resizedImage))
                {
                    graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

                    graphics.DrawImage(originalImage, 0, 0, newWidth, newHeight);
                }

                resizedImage.Save(outputImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }
    }
}

在这个示例中,ResizeImage 方法接受输入图像的路径,输出图像的路径,以及新的宽度和高度。它会加载原始图像,创建一个新的Bitmap对象,并使用Graphics类来将原始图像绘制到新的Bitmap中,同时指定新的宽度和高度。

请确保在你的项目中引用了System.Drawing程序集。

注意:在.NET Core 中,System.Drawing命名空间已经不推荐使用,而是建议使用System.Drawing.Common NuGet包。如果你在使用.NET Core,你可以通过在项目中安装System.Drawing.Common NuGet包来获得类似的功能。

您可能感兴趣:

阿里云 云服务器 99元1年 2核2G 3M固定带宽 续费与新购同价

领取 通义灵码 免费使用资格 兼容 Visual Studio Code、Visual Studio、JetBrains IDEs 等主流编程工具, 为你提供高效、流畅、舒心的智能编码体验!

DOVE 网络加速器 梯子 免费 试用

顶部