How to Resize Center and Crop an image with ImageSharp

So here's relevent code after so far after converting to not use original methods:

using (var fullSizeStream = new MemoryStream())
using (var smallStream = new MemoryStream())
using (var thumbStream = new MemoryStream())
using (var reviewThumbStream = new MemoryStream())
using (var image = Image.Load(inStream))
{
    // Save original constrained
    var clone = image.Clone(context => context
        .Resize(new ResizeOptions
        {
            Mode = ResizeMode.Max,
            Size = new Size(1280, 1280)
        }));
    clone.Save(fullSizeStream, new JpegEncoder { Quality = 80 });

    //Save three sizes Cropped:
    var jpegEncoder = new JpegEncoder { Quality = 75 };
    clone = image.Clone(context => context
        .Resize(new ResizeOptions
        {
            Mode = ResizeMode.Crop,
            Size = new Size(277, 277)
        }));
    clone.Save(smallStream, jpegEncoder);

    clone = image.Clone(context => context
        .Resize(new ResizeOptions
        {
            Mode = ResizeMode.Crop,
            Size = new Size(100, 100)
        }));
    clone.Save(thumbStream, jpegEncoder);

    clone = image.Clone(context => context
        .Resize(new ResizeOptions
        {
            Mode = ResizeMode.Crop,
            Size = new Size(50, 50)
        }));
    clone.Save(reviewThumbStream, jpegEncoder);

    //...then I just save the streams to blob storage
}

Yeah, super easy.

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);
}

EDIT If you want to leave the original image untouched you can use the Clone method instead.

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);
}

You might even be able to optimize this into a single method call to Resize via the overload that accepts a ResizeOptions instance with `ResizeMode.Crop. That would allow you to resize to a ratio then crop off any excess outside that ratio.

Tags:

C#

Imagesharp