简体   繁体   中英

SixLabors ImageSharp crop-resizes wrong width and height

I use SixLabors.ImageSharp to resize photo using below code:

https://www.nuget.org/packages/SixLabors.ImageSharp/
ASP .NET Core 5.0

Input photo: 720x960px
Expect output: 248x186px
Actual result: 186x248px

Why width becomes height and vice versa?

using (var stream = new MemoryStream())
{
    using var image = Image.Load(bytes);
    image.Mutate(x => x
        .Resize(new ResizeOptions
            {
                Mode = ResizeMode.Crop,
                Position = AnchorPositionMode.Center,
                Size = new Size(248, 186)
            })
        .BackgroundColor(Color.White));

    await image.SaveAsync(stream, new JpegEncoder() { Quality = 85 });
}

This will be because your source photo has a metadata flag that has a custom orientation set which causes clients to rotate the image when rendering it/interpreting but in fact the pixel data is really rotated 90 degrees than it appears.

You will want to use the .AutoOrient() api to fix that for you, that forces the pixels data to be oriented correctly to the desired orientation.

using (var stream = new MemoryStream())
{
    using var image = Image.Load(bytes);
    image.Mutate(x => x
        .AutoOrient() // this is the important thing that needed adding
        .Resize(new ResizeOptions
            {
                Mode = ResizeMode.Crop,
                Position = AnchorPositionMode.Center,
                Size = new Size(248, 186)
            })
        .BackgroundColor(Color.White));

    await image.SaveAsync(stream, new JpegEncoder() { Quality = 85 });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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