C#裁剪图像梯形/多边形
C# crop image trapezoid / polygon
我有一张图片,我想从一张图片中剪出一个梯形。
我有 8 个这样的不同坐标(8 个值形成一个有 4 个点的多边形)
pointA(222,222)
pointB(666,234)
pointC(678,235)
pointD(210,220)
我才知道如何使用 bitmap.Clone
像这样裁剪图像
var x = pointA.x;
var y = pointA.y;
var height = pointD.y - pointA.y;
var width = pointB.x - pointA.x;
Bitmap image = new Bitmap(imagepath);
var rect = new Rectangle(x, y, wight, height);
var newImage = image.Clone(rect, image.PixelFormat);
这将创建一个笔直的矩形,我要剪切的子部分的重要部分将消失。
那么,如何在控制台环境中使用 c# 和 .net Framework 核心裁剪梯形?
我想切出一个梯形,但我只是想出了更好的形式来描述我想要的多边形。
一种方法是使用 Graphics API. This has a FillPolygon method that takes a list of points and a brush. To use the source bitmap you would use the TextureBrush。把这些放在一起,你最终会得到这样的东西:
public Bitmap FillPolygon(Bitmap sourceBitmap, PointF[] polygonPoints)
{
var targetBitmap = new Bitmap(256, 256);
using var g = Graphics.FromImage(targetBitmap);
using var brush = new TextureBrush(sourceBitmap);
g.FillPolygon(brush, polygonPoints);
return targetBitmap;
}
我认为这应该可以在 windows 控制台上运行。在没有 windows 会话的情况下使用某些图形 API 一直存在一些问题,但我认为这不再是问题了。
为了获得最大的兼容性,您始终可以自己进行三角测量和 rasterize 梯形并复制所选像素,但这可能需要更多的工作。
我有一张图片,我想从一张图片中剪出一个梯形。
我有 8 个这样的不同坐标(8 个值形成一个有 4 个点的多边形)
pointA(222,222)
pointB(666,234)
pointC(678,235)
pointD(210,220)
我才知道如何使用 bitmap.Clone
像这样裁剪图像
var x = pointA.x;
var y = pointA.y;
var height = pointD.y - pointA.y;
var width = pointB.x - pointA.x;
Bitmap image = new Bitmap(imagepath);
var rect = new Rectangle(x, y, wight, height);
var newImage = image.Clone(rect, image.PixelFormat);
这将创建一个笔直的矩形,我要剪切的子部分的重要部分将消失。
那么,如何在控制台环境中使用 c# 和 .net Framework 核心裁剪梯形?
我想切出一个梯形,但我只是想出了更好的形式来描述我想要的多边形。
一种方法是使用 Graphics API. This has a FillPolygon method that takes a list of points and a brush. To use the source bitmap you would use the TextureBrush。把这些放在一起,你最终会得到这样的东西:
public Bitmap FillPolygon(Bitmap sourceBitmap, PointF[] polygonPoints)
{
var targetBitmap = new Bitmap(256, 256);
using var g = Graphics.FromImage(targetBitmap);
using var brush = new TextureBrush(sourceBitmap);
g.FillPolygon(brush, polygonPoints);
return targetBitmap;
}
我认为这应该可以在 windows 控制台上运行。在没有 windows 会话的情况下使用某些图形 API 一直存在一些问题,但我认为这不再是问题了。
为了获得最大的兼容性,您始终可以自己进行三角测量和 rasterize 梯形并复制所选像素,但这可能需要更多的工作。