在C#中调整图像大小可以使用System.Drawing
命名空间中的Bitmap
类和Graphics
类。以下是一个示例,演示如何调整图像大小:(当前例子不能跨平台,下面还有跨平台实例)
using System;
using System.Drawing;
class Program
{
static void Main()
{
string inputImagePath = "路径\\到\\你的\\输入图像.jpg";
string outputImagePath = "路径\\到\\你的\\输出图像.jpg";
// 调整图像大小
ResizeImage(inputImagePath, outputImagePath, 800, 600);
Console.WriteLine("图像调整大小完成。");
}
static void ResizeImage(string inputPath, string outputPath, int newWidth, int newHeight)
{
try
{
// 读取原始图像
using (Bitmap originalImage = new Bitmap(inputPath))
{
// 创建新的图像
using (Bitmap resizedImage = new Bitmap(newWidth, newHeight))
{
// 使用Graphics对象进行绘制
using (Graphics graphics = Graphics.FromImage(resizedImage))
{
// 设置插值模式以保持图像质量
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
// 绘制调整大小后的图像
graphics.DrawImage(originalImage, 0, 0, newWidth, newHeight);
// 保存调整大小后的图像
resizedImage.Save(outputPath);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"调整图像大小时发生错误:{ex.Message}");
}
}
}
上述代码中,ResizeImage
方法接收输入图像路径、输出图像路径以及新的宽度和高度。使用Graphics
对象进行图像的绘制,通过设置InterpolationMode
来保持调整大小后图像的质量。最后,保存调整大小后的图像。
在跨平台的C#应用程序中,你可以使用.NET Core或.NET 5及更高版本,并借助一些跨平台的图像处理库来实现图像大小调整。其中,一个流行的库是ImageSharp,它是一个跨平台的图像处理库,可以用于.NET应用程序。
以下是一个使用ImageSharp库的简单示例:
首先,需要在项目中安装ImageSharp NuGet 包:
dotnet add package SixLabors.ImageSharp
然后,可以使用以下代码进行图像大小调整:
using System;
using System.IO;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
class Program
{
static void Main()
{
string inputImagePath = "路径\\到\\你的\\输入图像.jpg";
string outputImagePath = "路径\\到\\你的\\输出图像.jpg";
// 调整图像大小
ResizeImage(inputImagePath, outputImagePath, 800, 600);
Console.WriteLine("图像调整大小完成。");
}
static void ResizeImage(string inputPath, string outputPath, int newWidth, int newHeight)
{
try
{
using (var image = Image.Load(inputPath))
{
// 调整图像大小
image.Mutate(x => x.Resize(new ResizeOptions
{
Size = new Size(newWidth, newHeight),
Mode = ResizeMode.Max // 或其他调整模式
}));
// 保存调整大小后的图像
image.Save(outputPath);
}
}
catch (Exception ex)
{
Console.WriteLine($"调整图像大小时发生错误:{ex.Message}");
}
}
}
这个示例使用ImageSharp库,该库支持在各种平台上进行图像处理,并提供了更多先进的图像处理功能。通过这种方式,你可以实现跨平台的图像大小调整,无论是在Windows、Linux还是macOS上。
源代码获取:公众号回复消息【code:68409
】