gpt4 book ai didi

c# - 在 C# 中使用 SixLabors.ImageSharp 裁剪和移动图片

转载 作者:行者123 更新时间:2023-12-03 08:44:25 26 4
gpt4 key购买 nike

我正在使用SixLabors.ImageSharp在 C# .NET Core 3.1 中以编程方式裁剪图像。您可以在下面找到一个有效的代码片段。

public static void ResizeImage(Image<Rgba32> input, Size dimensions)
{
var options = new ResizeOptions
{
Size = dimensions,
Mode = ResizeMode.Crop
};

input.Mutate(x => x.Resize(options));
}

它工作得很好,但我想允许用户根据一对给定的坐标裁剪图像。这意味着,裁剪将从这些坐标开始,而不是从原点 (0, 0) 开始。使用这个工具可以做到这一点吗?

到目前为止,我只能从图像一角开始裁剪。我希望能够从任何位置开始裁剪。例如,对于以下图像:

John Doe

用户想要通过在 x 和 y 轴上移动裁剪来裁剪图片的中心部分。最终结果是:

enter image description here

请注意,在给定的示例中,我已经切掉了图像的角点。用Imagesharp可以做到这一点吗?

最佳答案

使用Rectangle.FromLTRB

using (var inputStream = File.OpenRead(Path.Combine(inPath, "john-doe.png")))
using (var image = Image.Load<Rgba32>(inputStream))
{
// Generate some rough coordinates from the source.
// We'll take 25% off each edge.
var size = image.Size();
var l = size.Width / 4;
var t = size.Height / 4;
var r = 3 * (size.Width / 4);
var b = 3 * (size.Height / 4);

image.Mutate(x => x.Crop(Rectangle.FromLTRB(l, t, r, b)));

image.Save(Path.Combine(outPath, "john-doe-cropped.png"));
}

关于c# - 在 C# 中使用 SixLabors.ImageSharp 裁剪和移动图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62009383/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com