非矩形图像的Netvips裁剪图像问题

时间:2019-10-04 06:11:48

标签: c# image

我正在使用Netvips来裁剪图像并基于四个角点,但是仅靠顶部就不能裁剪图像,因为顶部宽度和底部宽度并不相同。

下面是提供的各种示例的代码和链接

Image image = Image.NewFromFile(args[0]);
string outFilename = args[1];
int topLeftX = int.Parse(args[2]);
int topLeftY = int.Parse(args[3]);
int topRightX = int.Parse(args[4]);
int topRightY = int.Parse(args[5]);
int bottomRightX = int.Parse(args[6]);
int bottomRightY = int.Parse(args[7]);

// the angle the top edge is rotated by
int dx = topRightX - topLeftX;
int dy = topRightY - topLeftY;
double angle = (180 / Math.PI) * Math.Atan2(dx, dy);
if (angle < -45 || angle >= 45)
{
    angle = 90 - angle;
}

// therefore the angle to rotate by to get it straight
angle = -angle;

image = image.Rotate(angle);

// the new position of the rectangle in the rotated image
double radians = (Math.PI * angle) / 180.0;
double c = Math.Cos(radians);
double s = Math.Sin(radians);

int left = Convert.ToInt32(topLeftX * c - topLeftY * s);
int top = Convert.ToInt32(topLeftX * s + topLeftY * c);
int width = Convert.ToInt32(Math.Sqrt(Math.Pow(topRightX - topLeftX, 2) +
                                      Math.Pow(topRightY - topLeftY, 2)));
int height = Convert.ToInt32(Math.Sqrt(Math.Pow(topRightX - bottomRightX, 2) +
                                       Math.Pow(topRightY - bottomRightY, 2)));

// after a rotate, the new position of the origin is given by .Xoffset, .Yoffset
Image tile = image.Crop(left + image.Xoffset, top + image.Yoffset, width, height);

tile.WriteToFile(outFilename);

示例图片-http://i.stack.imgur.com/x21me.png

0 个答案:

没有答案
相关问题