如何在 .NET core 中裁剪图像?

moh*_*eli 5 c# image .net-core imagesharp

我需要在 .NET Core 中裁剪图像。我使用了 ImageSharp、CoreCompat 和 Microsoft.Windows.Compatibility,并扫描了我能找到的所有方法。但是,我仍然找不到裁剪图像的方法。可以调整大小,但不能裁剪。

如何根据左上角的像素位置、宽度和高度在 .NET Core 中裁剪图像?

kml*_*kml 1

您可以使用ImageSharp 库。它具有基于左上角裁剪图像的方法。看下面的例子:

private async static Task CropImage()
{
    using (var httpClient = new HttpClient())
    {
        var response = await httpClient.GetAsync("https://assets-cdn.github.com/images/modules/logos_page/GitHub-Mark.png")
            .ConfigureAwait(false);

        using (var inputStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
        {
            using (var image = Image.Load(inputStream))
            {
                var path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "foo.png");

                image.Clone(
                    ctx => ctx.Crop(560, 300)).Save(path);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)