当前位置:网站首页>C# 去掉图片多余白色部分
C# 去掉图片多余白色部分
2022-07-19 16:50:00 【小慧哥】
/// <summary>
/// 裁剪图片(去掉百边)
/// </summary>
/// <param name="FilePath">图片路径</param>
public void RemoveWhiteEdge(string FilePath)
{
Bitmap bmp = new Bitmap(FilePath);
//上左右下
int top = 0, left = 0, right = bmp.Width, bottom = bmp.Height;
//寻找最上面的标线,从左(0)到右,从上(0)到下
for (int i = 0; i < bmp.Height; i++)//行
{
bool find = false;
for (int j = 0; j < bmp.Width; j++)//列
{
Color c = bmp.GetPixel(j, i);
if (!IsWhite(c))
{
top = i;
find = true;
break;
}
}
if (find)
break;
}
//寻找最左边的标线,从上(top位)到下,从左到右
for (int i = 0; i < bmp.Width; i++)//列
{
bool find = false;
for (int j = top; j < bmp.Height; j++)//行
{
Color c = bmp.GetPixel(i, j);
if (!IsWhite(c))
{
left = i;
find = true;
break;
}
}
if (find)
break;
}
//寻找最下边标线,从下到上,从左到右
for (int i = bmp.Height - 1; i >= 0; i--)//行
{
bool find = false;
for (int j = left; j < bmp.Width; j++)//列
{
Color c = bmp.GetPixel(j, i);
if (!IsWhite(c))
{
bottom = i;
find = true;
break;
}
}
if (find)
break;
}
//寻找最右边的标线,从上到下,从右往左
for (int i = bmp.Width - 1; i >= 0; i--)//列
{
bool find = false;
for (int j = 0; j <= bottom; j++)//行
{
Color c = bmp.GetPixel(i, j);
if (!IsWhite(c))
{
right = i;
find = true;
break;
}
}
if (find)
break;
}
//克隆位图对象的一部分。
Rectangle cloneRect = new Rectangle(left, top, right - left, bottom - top);
Bitmap cloneBitmap = bmp.Clone(cloneRect, bmp.PixelFormat);
cloneBitmap.Save(@"D:/service/123.png", ImageFormat.Png);
bmp.Dispose();
}
/// <summary>
/// 判断是否白色和纯透明色(10点的容差)
/// </summary>
public static bool IsWhite(Color c)
{
//纯透明也是白色,RGB都为255为纯白
if (c.A < 10 || (c.R > 245 && c.G > 245 && c.B > 245))
return true;
return false;
}
转自让梦想疯狂
边栏推荐
猜你喜欢
After graduating from college in 19 years, I chose software testing after recognizing the truth of life
ArcGIS/ArcPy将浮点类栅格转为整型栅格
多线程FTP项目(4)—— Mysql数据库 + FTP
LiDAR数据下载步骤
信通院《分布式存储发展白皮书(2022年)》发布:华云数据参与编制 为产业发展提速换挡
接口调试还能这么玩?
Matlab绘制散点密度图
%d,%s,%c,%x
MATLAB回归分析获取预测变量的系数和p值和R2(仅一行代码)
Is there a shortcut to the success of the test post? I tell you, the only shortcut is not to take detours
随机推荐
第十章:线程
LiDAR数据下载步骤
面试官:Redis&MySQL的三种缓存更新策略是怎样的?
Download method of European Meteorological Center data (ERA)
融云推出实时社区解决方案,垂直兴趣社交「高级玩家」上线
Huayun data won the outstanding contribution enterprise of sustainable technological innovation
Pycharm Debug错误“Process finished with exit code -1073741819 (0xC0000005)”解决方案
Delete the elements of array B in MATLAB array a
TRMM Precipitation Data Download steps
教你使用CANN将照片一键转换成卡通风格
What is enterprise firewall and what is strategy?
Matlab绘制散点密度图
MySQL migration gold warehouse database primary key, index loss solution
Matlab calculates the distance between two points (longitude and latitude coordinates) (large arc method and haversine method)
多线程FTP项目(4)—— Mysql数据库 + FTP
Geoscience Academic Resources II
ArcGIS/ArcPy将浮点类栅格转为整型栅格
ES6语法扩展与新特性
ASP function split() corresponds to PHP function explode() string variable array
Matlab填充影像中的无效值