Skip to content
Tutorials Center
My learning

Topics

Lesson 127 of 182 ยท Standard Library

Images with ImageSharp

Learn image processing in C#: load, resize, crop, convert and draw on images with SixLabors ImageSharp, plus how pixels work, shown with runnable pixel-buffer examples.

Almost every application touches images at some point: thumbnails for uploaded photos, a QR code on a ticket, a chart saved as a PNG, a watermark on a product picture. .NET itself has no cross-platform image library in the box. The old System.Drawing is Windows-only in practice (Microsoft documents it as such), so server code uses a third-party package. The most popular modern choice is SixLabors ImageSharp, a fully managed library with no native dependencies that runs on Windows, Linux, macOS and in containers.

This lesson explains how images are represented, shows the ImageSharp API for loading, resizing, cropping, drawing and saving, and gives practical advice for web apps. ImageSharp is a NuGet package that our in-browser runner does not include, so its code appears in read-only blocks. To keep the ideas hands-on, the runnable examples build the same operations from scratch on a tiny pixel buffer, which is also the best way to understand what the library does. Review arrays, streams and files and paths first.

ImageSharp is free for open-source and many small uses, but it has a split license (check the current terms on the SixLabors site) that requires a paid license for some commercial uses. Always read the license before using any package in a commercial product. Alternatives include SkiaSharp (wrapper around Google's Skia, native binaries), Magick.NET (ImageMagick) and NetVips.

How an image is stored

A raster image is a grid of pixels. Each pixel has a color, usually made from red, green, blue and alpha (transparency) channels of 8 bits each, written Rgba32. A 1920 x 1080 image has 2,073,600 pixels, which is about 8.3 MB in memory at 4 bytes per pixel, no matter how small the file on disk is. A JPEG that is 300 KB still costs 8 MB once decoded. That is why processing many large images in parallel can exhaust memory.

flowchart LR
    A["File on disk<br/>(JPEG, PNG, WebP)"] -->|"decode"| B["Pixel grid in memory<br/>width x height x 4 bytes"]
    B -->|"resize, crop, draw, filter"| C["Changed pixel grid"]
    C -->|"encode"| D["New file<br/>(JPEG, PNG, WebP)"]

Every image pipeline is decode, change pixels, encode.

File formats differ in what they are good at:

Format Compression Transparency Best for
JPEG Lossy No Photos
PNG Lossless Yes Screenshots, logos, graphics
WebP Lossy or lossless Yes Smaller files for the web
GIF Lossless, 256 colors 1-bit Simple animations

Setting up ImageSharp

You add the package to your project (this is a command for your terminal, not for the runner):

Terminal
dotnet add package SixLabors.ImageSharp
dotnet add package SixLabors.ImageSharp.Drawing

The core package loads, transforms and saves images. The Drawing package adds shapes and text. Namespaces you will use: SixLabors.ImageSharp, SixLabors.ImageSharp.Processing, SixLabors.ImageSharp.PixelFormats and SixLabors.ImageSharp.Formats.Jpeg (or .Png, .Webp).

Loading, resizing and saving

The core pattern is Image.Load, then Mutate to change the image in place, then Save. Image is IDisposable because it holds large pixel buffers, so wrap it in using (disposal).

C#
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.Processing;

using Image image = await Image.LoadAsync("photo.jpg");
Console.WriteLine($"{image.Width} x {image.Height}");

image.Mutate(ctx => ctx.Resize(new ResizeOptions
{
    Size = new Size(400, 300),
    Mode = ResizeMode.Crop        // fill the box, trim the overflow
}));

await image.SaveAsync("thumbnail.jpg", new JpegEncoder { Quality = 80 });

Resizing is where the options matter:

  • ResizeMode.Max keeps the aspect ratio and fits inside the box (a 4000 x 3000 photo in a 400 x 400 box becomes 400 x 300).
  • ResizeMode.Crop fills the whole box and cuts off what overflows, ideal for square avatars.
  • ResizeMode.Pad fits inside and fills the rest with a background color.
  • ResizeMode.Stretch distorts the picture to the new size. Rarely what you want.
  • Passing 0 for one dimension (ctx.Resize(400, 0)) keeps the aspect ratio automatically.

Other common operations are chained in the same Mutate call:

C#
image.Mutate(ctx => ctx
    .AutoOrient()                     // honor the camera's EXIF rotation
    .Crop(new Rectangle(100, 50, 800, 600))
    .Rotate(90)
    .Flip(FlipMode.Horizontal)
    .Grayscale()
    .GaussianBlur(2f)
    .Brightness(1.1f));

AutoOrient() deserves emphasis: phones store photos sideways and record the real orientation in EXIF metadata. Without AutoOrient, thumbnails of portrait photos often show up rotated. Also strip metadata (location, camera serial numbers) before publishing user photos: image.Metadata.ExifProfile = null;.

Creating, reading and writing pixels

To create an image from nothing, give it a size and, optionally, fill it. To read or change single pixels, use indexers or, much faster, row spans through ProcessPixelRows.

C#
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;

using var canvas = new Image<Rgba32>(200, 100, Color.White);

canvas[10, 20] = new Rgba32(255, 0, 0);              // red pixel at x=10, y=20

canvas.ProcessPixelRows(accessor =>
{
    for (int y = 0; y < accessor.Height; y++)
    {
        Span<Rgba32> row = accessor.GetRowSpan(y);
        for (int x = 0; x < row.Length; x++)
        {
            row[x].B = (byte)(x * 255 / row.Length);   // blue gradient
        }
    }
});

The Span<T> version avoids the checks and the overhead of per-pixel calls; see spans and memory.

Drawing shapes and text

With the Drawing package you can paint on an image: lines, rectangles, ellipses, polygons and text. Text needs a font; load one from a file or the system fonts (the SixLabors.Fonts package).

C#
using SixLabors.Fonts;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;

using var card = new Image<Rgba32>(400, 200, Color.FromRgb(30, 41, 59));

FontFamily family = new FontCollection().Add("fonts/Inter-Regular.ttf");
Font font = family.CreateFont(32);

card.Mutate(ctx => ctx
    .Fill(Color.SteelBlue, new RectangularPolygon(20, 20, 120, 60))
    .Draw(Color.White, 3f, new EllipsePolygon(300, 100, 50))
    .DrawText("Hello, ImageSharp", font, Color.White, new PointF(20, 120)));

await card.SaveAsPngAsync("card.png");

Useful details: colors can come from names (Color.SteelBlue), hex (Color.ParseHex("#336699")) or channels (Color.FromRgba(r, g, b, a)). In a Docker container, system fonts are often missing, so ship your font file with the app.

Understanding the operations by building them

Libraries hide the pixel math, but it is short enough to write yourself. The next example implements a mini image type with a byte per pixel (grayscale), drawing a filled rectangle and a diagonal line, and prints it as characters so you can see the result in the output panel.

C# A tiny image and drawing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The key insight is the index formula y * Width + x: a 2D image lives in a flat array, one row after another. That is exactly how ImageSharp stores pixels, and why row spans are so fast.

What resizing really does

To shrink or grow an image, every pixel of the new image asks "which pixel of the old image am I?". The simplest answer is the nearest pixel (nearest neighbor), which is fast but blocky. Better methods blend several source pixels: bilinear, bicubic and Lanczos, the default family in ImageSharp. Here is nearest-neighbor on an 8 x 4 pattern, enlarged and shrunk.

C# Nearest-neighbor resizing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Real resamplers do much more work per pixel, which is why resizing large photos is CPU-heavy, but the idea is the same: map each output pixel back to the input.

Image processing in web apps

  • Validate uploads. Check the size limit first, then let Image.IdentifyAsync read just the header (it returns width, height and format without decoding the pixels). Reject absurd dimensions: a tiny PNG can claim to be 60,000 x 60,000 pixels and demand 14 GB of memory ("decompression bomb"). ImageSharp lets you set limits in DecoderOptions.
  • Never trust file extensions or the client's content type. Detect the real format from the content.
  • Re-encode uploads instead of storing the original bytes. This drops hidden data and ensures consistent formats.
  • Generate thumbnails once, store them (disk or object storage) and serve them with long cache headers, instead of resizing on every request.
  • Use await image.SaveAsync(stream, encoder) to write straight to the response or a blob storage stream, not through temporary files.
  • Limit concurrency. Resizing is CPU and memory heavy. Use a channel-based queue or SemaphoreSlim to process only a few images at a time.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A 1000 x 1000 JPEG is 80 KB on disk. Roughly how much memory does the decoded image use at 4 bytes per pixel?

    Memory is width x height x bytes per pixel: 1,000,000 x 4 = 4 MB, no matter how well the file was compressed on disk.
  2. 2. Why call AutoOrient() before resizing a phone photo?

    Cameras often store pixels in landscape order and note the real orientation in EXIF metadata. AutoOrient rotates the pixels accordingly.
  3. 3. Which ResizeMode fills a fixed box completely and trims what overflows?

    Crop scales the image until the box is covered and cuts off the excess, which suits square avatars. Max and Pad keep the whole picture; Stretch distorts it.
  4. 4. In a flat pixel array, where is the pixel at column x and row y?

    Rows are stored one after another, so you skip y complete rows of width pixels and then x more.
  5. 5. How can a user-uploaded image become a denial-of-service risk?

    Compressed formats can describe enormous images in a few kilobytes. Check dimensions with Image.IdentifyAsync and set decoder limits before decoding.

Summary

  • Decoded images cost width x height x 4 bytes of memory, regardless of file size.
  • ImageSharp is a managed cross-platform library: Image.Load, Mutate, Save, with Resize, Crop, AutoOrient and many filters.
  • Add ImageSharp.Drawing and a font file for shapes and text; check the library's license for commercial use.
  • Pixels live in a flat array indexed by y * width + x; row spans make pixel loops fast.
  • In web apps validate uploads, identify before decoding, re-encode, cache thumbnails and limit concurrency.

Next lesson: dependency injection.