Skip to content

ImageSharp

UI & GraphicsGraphics / Image ProcessingC#

What it is

ImageSharp is a fully managed, cross-platform 2D graphics library for .NET, handling decoding, resizing, format conversion and drawing with no native dependencies.

Load an image, apply a chain of mutations, and save in any supported format. Everything is managed code, so it works on Linux containers without extra packages.

Installation

dotnet add package SixLabors.ImageSharp

Getting started

The smallest useful thing you can do with it, and what each part means.

Resize and convert
using var image = await Image.LoadAsync(inputStream);

image.Mutate(x => x
    .AutoOrient()                       // honour the EXIF rotation flag
    .Resize(new ResizeOptions
    {
        Size = new Size(800, 600),
        Mode = ResizeMode.Max,          // preserve aspect ratio
        Sampler = KnownResamplers.Lanczos3,
    }));

await image.SaveAsWebpAsync(outputStream, new WebpEncoder { Quality = 80 });
AutoOrient is essential for user uploads: phone photos carry an EXIF orientation flag, and skipping it produces sideways thumbnails.

Advanced usage

Where the library earns its place over a simpler alternative.

Guarding against decompression bombs
// Read dimensions without decoding the pixels.
var info = await Image.IdentifyAsync(stream);
if (info.Width * (long)info.Height > 50_000_000)
    throw new InvalidOperationException("image too large");
stream.Position = 0;

// Cap memory the decoder may allocate.
var options = new DecoderOptions
{
    MaxFrames = 1,
    TargetSize = new Size(2000, 2000),
};
using var image = await Image.LoadAsync(options, stream);

image.Metadata.ExifProfile = null;   // strip EXIF, including GPS location
A small file can decode to gigabytes of pixels — a classic denial-of-service vector. Identify first, and strip EXIF before serving user images publicly, since it can contain GPS coordinates.

Errors and fixes

The failures you are most likely to hit, and what actually resolves them.

Image cannot be loaded / unknown format
The stream is not at position 0, or the format's decoder package is not referenced. Reset the stream and check the format.
Out of memory processing an upload
A decompression bomb. Use Image.Identify to check dimensions before decoding, and set DecoderOptions limits.

Best practices

  • Call AutoOrient on user-supplied photos or they will appear rotated.
  • Check dimensions with Identify before decoding untrusted uploads.
  • Strip EXIF metadata from images you republish; it may include location data.
  • Review the licence — commercial use outside an open-source project requires a paid licence.

Background

Why it exists, and what it was reacting to.

ImageSharp replaced System.Drawing.Common, which wrapped GDI+ and was formally unsupported on non-Windows platforms from .NET 6 onward. Being pure managed code, it runs identically everywhere.