简体   繁体   English

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

[英]Cropping and moving pictures with SixLabors.ImageSharp in C#

I am using the SixLabors.ImageSharp to programatically crop an image in C# .NET Core 3.1.我正在使用SixLabors.ImageSharp以编程方式裁剪 C# .NET Core 3.1 中的图像。 Below you can find a working code snippet.您可以在下面找到一个有效的代码片段。

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

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

It works really well, but I would like to allow the user to crop the image based on a pair of given coordinates.它工作得很好,但我想允许用户根据一对给定的坐标裁剪图像。 Meaning that, the cropping would start from those coordinates, and not from the origin (0, 0).这意味着,裁剪将从这些坐标开始,而不是从原点 (0, 0) 开始。 Is it possible to do so with this tool?用这个工具可以做到吗?

So far I could only crop starting from an image corner.到目前为止,我只能从图像角落开始裁剪。 I want to be able to crop starting from any position.我希望能够从任何 position 开始进行裁剪。 For example, for the following image:例如,对于以下图像:

约翰·多伊

A user wants to crop the central part of the picture, by shifting the cropping in the x and y axis.用户想要通过在 x 和 y 轴上移动裁剪来裁剪图片的中心部分。 Final result would be:最终结果将是:

在此处输入图像描述

Notice that I have cut the corners of the image, in the given example.请注意,在给定的示例中,我已经剪掉了图像的角落。 Is it possible to do so with Imagesharp?使用Imagesharp可以做到这一点吗?

Use Rectangle.FromLTRB使用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"));
}

Even though James' answer pointed me in the right direction, and also before in our brief conversation in the Imagesharp's gitter discussion , what solved the problem for me was the following code:尽管詹姆斯的回答为我指明了正确的方向,而且在我们之前在Imagesharp 的 gitter 讨论中的简短对话中,为我解决问题的是以下代码:

private static void ResizeImage(Image<Rgba32> input, int width, int height, int x, int y)
    {
        input.Mutate(img => img.Crop(Rectangle.FromLTRB(x, y, width+x, height+y)));
    }

In this code, I am shifting the original image in the x and y axis, and cropping the image by the given width and height .在这段代码中,我在xy轴上移动原始图像,并按给定的widthheight裁剪图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM