我需要转换一些基于System.Drawing的代码才能使用此.NET Core兼容库:

https://github.com/SixLabors/ImageSharp

下面基于System.Drawing的代码调整了图像的大小和边缘的裁剪,返回了要保存的内存流。 ImageSharp库是否可能?

private static Stream Resize(Stream inStream, int newWidth, int newHeight)
{
    var img = Image.Load(inStream);
    if (newWidth != img.Width || newHeight != img.Height)
    {
        var ratioX = (double)newWidth / img.Width;
        var ratioY = (double)newHeight / img.Height;
        var ratio = Math.Max(ratioX, ratioY);
        var width = (int)(img.Width * ratio);
        var height = (int)(img.Height * ratio);

        var newImage = new Bitmap(width, height);
        Graphics.FromImage(newImage).DrawImage(img, 0, 0, width, height);
        img = newImage;

        if (img.Width != newWidth || img.Height != newHeight)
        {
            var startX = (Math.Max(img.Width, newWidth) - Math.Min(img.Width, newWidth)) / 2;
            var startY = (Math.Max(img.Height, newHeight) - Math.Min(img.Height, newHeight)) / 2;
            img = Crop(img, newWidth, newHeight, startX, startY);
        }
    }

    var ms = new MemoryStream();
    img.Save(ms, ImageFormat.Jpeg);
    ms.Position = 0;
    return ms;
}

private static Image Crop(Image image, int newWidth, int newHeight, int startX = 0, int startY = 0)
{
    if (image.Height < newHeight)
        newHeight = image.Height;

    if (image.Width < newWidth)
        newWidth = image.Width;

    using (var bmp = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb))
    {
        bmp.SetResolution(72, 72);
        using (var g = Graphics.FromImage(bmp))
        {
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            g.DrawImage(image, new Rectangle(0, 0, newWidth, newHeight), startX, startY, newWidth, newHeight, GraphicsUnit.Pixel);

            var ms = new MemoryStream();
            bmp.Save(ms, ImageFormat.Jpeg);
            image.Dispose();
            var outimage = Image.FromStream(ms);
            return outimage;
        }
    }
}

最佳答案

是的, super 容易。

using (var inStream = ...)
using (var outStream = new MemoryStream())
using (var image = Image.Load(inStream, out IImageFormat format))
{
    image.Mutate(
        i => i.Resize(width, height)
              .Crop(new Rectangle(x, y, cropWidth, cropHeight)));

    image.Save(outStream, format);
}

编辑
如果要保持原始图像不变,可以改用Clone方法。

using (var inStream = ...)
using (var outStream = new MemoryStream())
using (var image = Image.Load(inStream, out IImageFormat format))
{
    var clone = image.Clone(
                    i => i.Resize(width, height)
                          .Crop(new Rectangle(x, y, cropWidth, cropHeight)));

    clone.Save(outStream, format);
}

您甚至可以通过重载将其优化为对 Resize 的单个方法调用,该重载接受带有`ResizeMode.Crop的ResizeOptions实例。这样一来,您就可以将尺寸调整为某个比例,然后裁剪掉超出该比例的所有多余部分。

09-25 19:24