C# 按指定宽高缩放图片
/// <summary>
/// 按指定宽高缩放图片
/// </summary>
/// <param name="image">原图片</param>
/// <param name="dstWidth">目标图片宽</param>
/// <param name="dstHeight">目标图片高</param>
/// <returns></returns>
public Image ScaleImage(Image image, int dstWidth, int dstHeight)
{
Graphics g = null;
try
{
//按比例缩放
float scaleRate = GetWidthAndHeight(image.Width, image.Height, dstWidth, dstHeight);
int width = (int)(image.Width * scaleRate);
int height = (int)(image.Height * scaleRate);
Bitmap destBitmap = new Bitmap(width, height);
g = Graphics.FromImage(destBitmap);
g.Clear(Color.Transparent);
//设置画布的描绘质量
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(image, new Rectangle(0, 0, width, height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
return destBitmap;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
finally
{
if (g != null)
{
g.Dispose();
}
if (image != null)
{
image.Dispose();
}
}
}
/// <summary>
/// 获取图片缩放比例
/// </summary>
/// <param name="oldWidth">原图片宽</param>
/// <param name="oldHeigt">原图片高</param>
/// <param name="newWidth">目标图片宽</param>
/// <param name="newHeight">目标图片高</param>
/// <returns></returns>
public float GetWidthAndHeight(int oldWidth, int oldHeigt, int newWidth, int newHeight)
{
//按比例缩放
float scaleRate;
if (oldWidth >= newWidth && oldHeigt >= newHeight)
{
int widthDis = oldWidth - newWidth;
int heightDis = oldHeigt - newHeight;
if (widthDis > heightDis)
{
scaleRate = newWidth * 1f / oldWidth;
}
else
{
scaleRate = newHeight * 1f / oldHeigt;
}
}
else if (oldWidth >= newWidth)
{
scaleRate = newWidth * 1f / oldWidth;
}
else if (oldHeigt >= newHeight)
{
scaleRate = newHeight * 1f / oldHeigt;
}
else
{
int widthDis = newWidth - oldWidth;
int heightDis = newHeight - oldHeigt;
if (widthDis > heightDis)
{
scaleRate = newHeight * 1f / oldHeigt;
}
else
{
scaleRate = newWidth * 1f / oldWidth;
}
}
return scaleRate;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?