图像的处理 图片裁剪工具方法 图片按比例缩放的工具方法

/// <summary>

/// 图片裁剪工具方法

/// </summary>

/// <param name="Bitmap"></param>

/// <param name="Rect"></param>

/// <returns></returns>

public static Bitmap CutImage(Bitmap Bitmap, ref Rectangle Rect)

{

if (Rect.X < 0)

{

Rect.X = 0;

}

if (Rect.Y < 0)

{

Rect.Y = 0;

}

if (Rect.X + Rect.Width > Bitmap.Width)

{

Rect.Width = Bitmap.Width - Rect.X;

}

if (Rect.Y + Rect.Height > Bitmap.Height)

{

Rect.Height = Bitmap.Height - Rect.Y;

}

if (0 == Rect.Width)

{

Rect.Width = 4;

}

if (0 == Rect.Height)

{

Rect.Height = 4;

}

return Bitmap.Clone(Rect, Bitmap.PixelFormat);

}

/// <summary>

/// 图片按比例缩放的工具方法

/// </summary>

/// <param name="bitmap"></param>

/// <param name="Scale"></param>

/// <returns></returns>

public static Bitmap ResizeImage(Bitmap bitmap, float Scale = 1f)

{

try

{

if (null != bitmap)

{

int w = bitmap.Width;

}

}

catch (ArgumentException)//图像被释放了

{

bitmap = null;

}

if (1f == Scale || null == bitmap)

{

return bitmap;

}

Bitmap result;

try

{

int width = (int)(bitmap.Width * Scale);

int height = (int)(bitmap.Height * Scale);

Bitmap bitmap2 = new Bitmap(width, height);

Graphics graphics = Graphics.FromImage(bitmap2);

graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

graphics.CompositingQuality = CompositingQuality.HighSpeed;

graphics.DrawImage(bitmap, new Rectangle(0, 0, width, height), new Rectangle(0, 0, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel);

graphics.Dispose();

result = bitmap2;

}

catch

{

result = bitmap;

}

return result;

}

相关推荐
武藤一雄2 分钟前
C#:nameof 运算符全指南
开发语言·microsoft·c#·.net·.netcore
CSharp精选营2 小时前
聊一聊 C# 中的闭包陷阱:foreach 循环的坑你还记得吗?
c#·foreach·循环·for循环
月巴月巴白勺合鸟月半2 小时前
FHIR 的使用
人工智能·c#·fhir
公子小六2 小时前
基于.NET的Windows窗体编程之WinForms控件简介
windows·microsoft·c#·.net
观无4 小时前
mysql5.7下载地址
c#
武藤一雄4 小时前
C# 核心技术解析:Parse vs TryParse 实战指南
开发语言·windows·microsoft·微软·c#·.netcore
代数狂人4 小时前
在Godot中应用面向对象原则:C#脚本实践
c#·游戏引擎·godot
斌味代码4 小时前
RAG 实战:用 LangChain + DeepSeek 搭建企业私有知识库问答系统
开发语言·langchain·c#
张人玉5 小时前
C#类常用知识总结Pro
服务器·c#
武藤一雄6 小时前
深入理解 C# 中的 sizeof 与非托管类型约束
开发语言·windows·c#·.net·.netcore