c# - 倾斜图像后 GDI C# 删除背景
问题描述
我正在尝试从输入的方形图像制作具有透明背景的倾斜图像。
到目前为止,倾斜部分正在工作,但未倾斜图像的背景仍然存在。如何从背景中删除未倾斜的图像并将其替换为透明背景?
到目前为止,我已经尝试过使用.Clear(Color.Transparent)
,但它似乎只能使整个图像清晰或什么都不做。
到目前为止的代码:
using System;
using System.Drawing;
class Program
{
static void Main(string[] args)
{
Point[] destinationPoints = {
new Point (150, 20),
new Point (40, 50),
new Point (150, 300)
};
Image before = Image.FromFile(System.IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"before.png"));
var gr = Graphics.FromImage(before);
//drawing an ellipse
Pen myPen = new Pen(Color.Red);
gr.DrawEllipse(myPen, new Rectangle(0, 0, 200, 300));
//applying skewed points
gr.DrawImage(before, destinationPoints);
var path = System.IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"after.png");
before.Save(path);
}
}
之前.png
之后.png
粗略的预期结果
解决方案
我试过使用
Graphics.Clear(Color.Transparent)
,但它似乎只清除整个图像
确实; 您需要先选择要清除的部分,除了您绘制的部分倾斜之外,这是所有内容..:
using System.Drawing.Drawing2D;
..
GraphicsPath gp = new GraphicsPath();
gp.AddRectangle(new Rectangle(Point.Empty, before.Size));
gp.AddPolygon(destinationPoints);
这首先选择整个图像,然后在倾斜的目标区域切一个洞。
(注意:GraphicsPath只允许您添加到它包含的图形;默认缠绕模式的规则是:添加区域,除非它们与已经存在的区域重叠。一旦减去重叠的部分等。)
现在您有两个选项来清除图像的未倾斜部分。
您可以填充透明:
gr.CompositingMode = CompositingMode.SourceOver;
gr.FillPath(Brushes.Transparent, gp);
或者你可以 用透明的方式清除:
gr.SetClip(gp);
gr.Clear(Color.Transparent);
这应该适用于您的示例图像。
不幸的是,一旦您的图像在倾斜部分包含非透明像素,这将不起作用。在这里,原始像素仍然会发光。
所以这种情况的解决方案相当简单:不要在原始位图上绘制,而是使用您希望的背景色创建一个新的位图并在新的位图上绘制:
Image after = new Bitmap(before.Width, before.Height);
var gr = Graphics.FromImage(after );
gr.Clear(Color.yourChoice);
// now draw as needed..
推荐阅读
- node.js - 我可以将 mongodb _id 添加到 localhost 地址以显示数据库中的一篇文章吗?
- javascript - JavaScript如何修改数组中的数字
- python - CSS 引用许多样式表和可扩展性
- machine-learning - sklearn 中随机森林分类器中组件树的数量(或估计器的数量)如何影响其准确性?
- python-3.x - 估计所有面覆盖的区域
- gitlab - 尽管有效的正则表达式和激活的解析,gitlab 中没有覆盖率报告
- php - 我无法使用 elasticsearch-php 包连接到 Elasticsearch
- reactjs - 如何使用来自useEffect的事件调用函数
- mysql - 如何比较同一表中多个项目的日期之间的数据
- powershell - Powershell 脚本生成数百万次调用 __PSLockdownPolicy