Images
suggest change.NET has no cross-platform image library built in, so loading, resizing and converting images means picking a package:
- SixLabors.ImageSharp is fully managed C#. No native dependencies, so it runs the same on Windows, Linux, macOS, in Docker and on Azure Functions. It reads and writes JPEG, PNG, WebP, GIF, BMP, TIFF, TGA, QOI and more. The companion package SixLabors.ImageSharp.Drawing draws shapes and text.
- SkiaSharp wraps Google's Skia, the native 2D engine used by Chrome and Android. It's fast and maintained by Microsoft, but ships native binaries for each platform.
- System.Drawing.Common (GDI+) is the old .NET Framework API (
Bitmap,Graphics). Since .NET 6 it's supported on Windows only. Don't use it in new server code. - Magick.NET wraps ImageMagick. Use it when you need formats the others don't support (PSD, RAW, HEIC, PDF via Ghostscript).
This article uses ImageSharp for most examples and shows SkiaSharp at the end. Examples use C# 14 / .NET 10 as file-based programs (dotnet run app.cs). In a project, add the package with dotnet add package SixLabors.ImageSharp.
Licensing
ImageSharp is under the Six Labors Split License: free (Apache 2.0) for open source projects and for companies under 1M USD annual revenue, otherwise you need a commercial license. Version 4 checks for a license key at build time. Without one, Debug builds print a warning and Release builds fail:
warning : No Six Labors license found. This Debug build can continue, but Release builds require a valid license.
warning : Set SixLaborsLicenseKey, set SixLaborsLicenseFile, or add 'sixlabors.lic' to your project.
Get a key at sixlabors.com and set the SixLaborsLicenseKey MSBuild property (or put a sixlabors.lic file in the project directory). The outputs below omit this warning. ImageSharp 3.1.x has no key check, and SkiaSharp is MIT licensed.
Creating and saving an image
Image<TPixel> is an image whose pixels are stored as TPixel, a struct like Rgba32 (4 bytes: red, green, blue, alpha) or Rgb24. The indexer reads and writes single pixels:
#:package SixLabors.ImageSharp@4.1.3
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
// 640x480 image with a red-to-blue gradient
using var image = new Image<Rgba32>(640, 480);
for (int y = 0; y < image.Height; y++)
{
for (int x = 0; x < image.Width; x++)
{
byte r = (byte)(255 * x / (image.Width - 1));
byte g = (byte)(255 * y / (image.Height - 1));
image[x, y] = new Rgba32(r, g, (byte)(255 - r));
}
}
image.Save("gradient.png"); // format chosen from the extension
image.Save("gradient.jpg");
image.SaveAsWebp("gradient.webp");
foreach (var f in new[] { "gradient.png", "gradient.jpg", "gradient.webp" })
{
Console.WriteLine($"{f,-14} {new FileInfo(f).Length,7:N0} bytes");
}
gradient.png 2,424 bytes
gradient.jpg 12,458 bytes
gradient.webp 3,044 bytes
Images hold large pixel buffers rented from a memory pool, so they implement IDisposable. Always create them with using (see Using Statement). A forgotten Dispose doesn't leak forever, but it keeps tens of megabytes alive until the garbage collector runs a finalizer.
Save(path) picks the encoder from the file extension. There are also SaveAsPng, SaveAsJpeg, SaveAsWebp, SaveAsGif etc., which take a path or a Stream, and async versions of all of them.
Loading and identifying images
#:package SixLabors.ImageSharp@4.1.3
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
foreach (var path in new[] { "gradient.png", "gradient.jpg", "gradient.webp" })
{
// reads only the header, doesn't decode pixels
ImageInfo info = Image.Identify(path);
Console.WriteLine($"{path,-14} {info.Metadata.DecodedImageFormat?.Name,-5} " +
$"{info.Width}x{info.Height} {info.PixelType.BitsPerPixel} bpp");
}
// the format is detected from the content, not the file extension
File.WriteAllText("fake.png", "not really an image");
try
{
using Image bad = Image.Load("fake.png");
}
catch (UnknownImageFormatException)
{
Console.WriteLine("fake.png: unknown image format");
}
// Image: pixel format chosen by the decoder
using Image any = Image.Load("gradient.jpg");
Console.WriteLine($"Load: Image<{any.GetType().GenericTypeArguments[0].Name}> {any.Width}x{any.Height}");
// Image<TPixel>: converted to the pixel format you ask for
using Image<Rgba32> rgba = Image.Load<Rgba32>("gradient.jpg");
Console.WriteLine($"Load<Rgba32>: Image<{rgba.GetType().GenericTypeArguments[0].Name}> {rgba.Width}x{rgba.Height}");
gradient.png PNG 640x480 32 bpp
gradient.jpg JPEG 640x480 24 bpp
gradient.webp WEBP 640x480 24 bpp
fake.png: unknown image format
Load: Image<Rgb24> 640x480
Load<Rgba32>: Image<Rgba32> 640x480
Image.Identify is cheap: it reads a few hundred bytes of header. Use it to get dimensions for an HTML width/height attribute or to reject huge images before decoding them.
Use the non-generic Image when you only resize and re-save. Use Image<TPixel> when you touch pixels and need to know their layout. Corrupt data throws InvalidImageContentException, unrecognized data throws UnknownImageFormatException.
Resizing, cropping and rotating
Operations are applied with Mutate, which changes the image in place, or Clone, which returns a new image and leaves the original alone. Both take a lambda that chains operations. The examples below use photo.jpg, a 3840x2401 photo.
#:package SixLabors.ImageSharp@4.1.3
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using Image image = Image.Load("gradient.jpg"); // 640x480
// height 0 means "keep the aspect ratio"
using (Image copy = image.Clone(x => x.Resize(320, 0)))
Console.WriteLine($"Resize(320, 0): {copy.Width}x{copy.Height}");
// fit into a 200x200 box
var opts = new ResizeOptions { Size = new Size(200, 200) };
foreach (var mode in new[] { ResizeMode.Max, ResizeMode.Crop, ResizeMode.Pad, ResizeMode.Stretch, ResizeMode.Min })
{
opts.Mode = mode;
using Image copy = image.Clone(x => x.Resize(opts));
Console.WriteLine($"{mode,-8} 200x200: {copy.Width}x{copy.Height}");
}
using (Image copy = image.Clone(x => x.Resize(new ResizeOptions
{
Size = new Size(1000, 1000),
Mode = ResizeMode.Max,
})))
Console.WriteLine($"Max 1000x1000: {copy.Width}x{copy.Height} (upscaled)");
using (Image copy = image.Clone(x => x
.Crop(new Rectangle(100, 50, 300, 200))
.Rotate(RotateMode.Rotate90)
.Flip(FlipMode.Horizontal)))
Console.WriteLine($"crop+rotate: {copy.Width}x{copy.Height}");
using (Image copy = image.Clone(x => x.Rotate(30)))
Console.WriteLine($"Rotate(30): {copy.Width}x{copy.Height}");
image.Mutate(x => x.Resize(new ResizeOptions
{
Size = new Size(128, 128),
Mode = ResizeMode.Max,
Sampler = KnownResamplers.Lanczos3,
}));
Console.WriteLine($"mutated in place: {image.Width}x{image.Height}");
Resize(320, 0): 320x240
Max 200x200: 200x150
Crop 200x200: 200x200
Pad 200x200: 200x200
Stretch 200x200: 200x200
Min 200x200: 267x200
Max 1000x1000: 1000x750 (upscaled)
crop+rotate: 200x300
Rotate(30): 795x736
mutated in place: 128x96
The resize modes:
- Max: fit inside the box, keep the aspect ratio. This is what you want for thumbnails and "longest side 1024" limits. It does upscale small images, so check the size first if you don't want that.
- Crop: fill the box exactly, cut off what sticks out. Good for square avatars.
ResizeOptions.Position(default center) orCenterCoordinateschoose which part stays. - Pad: fit inside the box and fill the rest with
PadColor(transparent by default). - Stretch: ignore the aspect ratio.
- Min: resize until the shorter side matches, never upscales.
The default sampler is Bicubic. Lanczos3 is a bit sharper for big reductions, NearestNeighbor keeps hard edges for pixel art.
Rotate by an arbitrary angle grows the canvas so nothing is cut off. Crop throws ArgumentException if the rectangle isn't inside the image.
Thumbnails
A complete thumbnail function: auto-orient, resize, strip metadata, save as JPEG:
#:package SixLabors.ImageSharp@4.1.3
using System.Diagnostics;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.Processing;
static void MakeThumbnail(string src, string dst, int maxSize)
{
using Image image = Image.Load(src);
image.Mutate(x => x
.AutoOrient() // apply the EXIF orientation of phone photos
.Resize(new ResizeOptions { Size = new Size(maxSize, maxSize), Mode = ResizeMode.Max }));
image.Metadata.ExifProfile = null; // strip camera data, GPS location etc.
image.SaveAsJpeg(dst, new JpegEncoder { Quality = 80 });
}
static void MakeThumbnailFast(string src, string dst, int maxSize)
{
// let the decoder downscale while decoding
var options = new DecoderOptions { TargetSize = new Size(maxSize, maxSize) };
using Image image = Image.Load(options, src);
image.Mutate(x => x
.AutoOrient()
.Resize(new ResizeOptions { Size = new Size(maxSize, maxSize), Mode = ResizeMode.Max }));
image.Metadata.ExifProfile = null;
image.SaveAsJpeg(dst, new JpegEncoder { Quality = 80 });
}
MakeThumbnail("photo.jpg", "warmup.jpg", 256);
MakeThumbnailFast("photo.jpg", "warmup.jpg", 256);
var sw = Stopwatch.StartNew();
MakeThumbnail("photo.jpg", "thumb.jpg", 256);
Console.WriteLine($"full decode: {sw.ElapsedMilliseconds} ms");
sw.Restart();
MakeThumbnailFast("photo.jpg", "thumb-fast.jpg", 256);
Console.WriteLine($"TargetSize: {sw.ElapsedMilliseconds} ms");
foreach (var f in new[] { "photo.jpg", "thumb.jpg", "thumb-fast.jpg" })
{
var info = Image.Identify(f);
Console.WriteLine($"{f,-15} {info.Width}x{info.Height} {new FileInfo(f).Length,10:N0} bytes");
}
full decode: 370 ms
TargetSize: 40 ms
photo.jpg 3840x2401 1,150,704 bytes
thumb.jpg 256x160 8,588 bytes
thumb-fast.jpg 256x161 8,682 bytes
DecoderOptions.TargetSize lets the JPEG decoder skip most of the work by decoding at 1/2, 1/4 or 1/8 scale. The result is at least as big as the target, so you still call Resize to get the exact size. For a large photo that's roughly a 9x speedup and much less memory.
Formats and encoder options
Pass an encoder to control quality and compression:
#:package SixLabors.ImageSharp@4.1.3
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.Formats.Webp;
using Image image = Image.Load("photo.jpg");
foreach (int q in new[] { 95, 75, 50, 20 })
{
using var ms = new MemoryStream();
image.SaveAsJpeg(ms, new JpegEncoder { Quality = q });
Console.WriteLine($"JPEG quality {q,3}: {ms.Length,9:N0} bytes");
}
var encoders = new (string Name, IImageEncoder Encoder)[]
{
("PNG default", new PngEncoder()),
("PNG best", new PngEncoder { CompressionLevel = PngCompressionLevel.BestCompression }),
("WebP lossy 75", new WebpEncoder { FileFormat = WebpFileFormatType.Lossy, Quality = 75 }),
("WebP lossless", new WebpEncoder { FileFormat = WebpFileFormatType.Lossless }),
};
foreach (var (name, encoder) in encoders)
{
using var ms = new MemoryStream();
image.Save(ms, encoder);
Console.WriteLine($"{name,-17} {ms.Length,9:N0} bytes");
}
JPEG quality 95: 1,548,559 bytes
JPEG quality 75: 765,557 bytes
JPEG quality 50: 548,719 bytes
JPEG quality 20: 380,250 bytes
PNG default 5,066,515 bytes
PNG best 5,028,009 bytes
WebP lossy 75 276,392 bytes
WebP lossless 3,305,364 bytes
Rules of thumb:
- Photos: JPEG quality 75-85, or lossy WebP, which is usually much smaller at the same visual quality and supported by every current browser.
- Screenshots, logos, line art: PNG or lossless WebP. JPEG blurs sharp edges and has no transparency.
- PNG compression level only trades CPU time for a few percent of size. It's always lossless.
JPEG has no alpha channel. Converting a transparent PNG to JPEG turns transparent pixels black unless you flatten onto a background first:
#:package SixLabors.ImageSharp@4.1.3
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
// a PNG that is transparent except for a red square
using (var png = new Image<Rgba32>(100, 100))
{
for (int y = 25; y < 75; y++)
for (int x = 25; x < 75; x++)
png[x, y] = new Rgba32(255, 0, 0);
png.SaveAsPng("logo.png");
}
using Image image = Image.Load("logo.png");
image.SaveAsJpeg("logo-black.jpg"); // JPEG has no alpha channel
image.Mutate(x => x.BackgroundColor(Color.White));
image.SaveAsJpeg("logo-white.jpg", new JpegEncoder { Quality = 90 });
foreach (var f in new[] { "logo-black.jpg", "logo-white.jpg" })
{
using var img = Image.Load<Rgb24>(f);
Console.WriteLine($"{f}: corner pixel {img[0, 0]}");
}
logo-black.jpg: corner pixel Rgb24(0, 0, 0)
logo-white.jpg: corner pixel Rgb24(255, 255, 255)
Filters and watermarks
ImageSharp has the usual set of filters. Each one is an extension method on IImageProcessingContext, so it can be chained with resizing:
#:package SixLabors.ImageSharp@4.1.3
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using Image photo = Image.Load("photo.jpg");
photo.Mutate(x => x.Resize(800, 0));
var effects = new Dictionary<string, Action<IImageProcessingContext>>
{
["grayscale"] = x => x.Grayscale(),
["sepia"] = x => x.Sepia(),
["blur"] = x => x.GaussianBlur(5),
["sharpen"] = x => x.GaussianSharpen(2),
["brighter"] = x => x.Brightness(1.4f).Contrast(1.2f),
["pixelate"] = x => x.Pixelate(16),
["invert"] = x => x.Invert(),
["vignette"] = x => x.Vignette(),
};
foreach (var (name, effect) in effects)
{
using Image copy = photo.Clone(effect);
copy.SaveAsJpeg($"photo-{name}.jpg");
Console.WriteLine($"photo-{name}.jpg");
}
// watermark: draw a semi-transparent logo in the bottom-right corner
using Image logo = Image.Load("drawing.png");
logo.Mutate(x => x.Resize(200, 0));
var pos = new Point(photo.Width - logo.Width - 10, photo.Height - logo.Height - 10);
photo.Mutate(x => x.DrawImage(logo, pos, opacity: 0.6f));
photo.SaveAsJpeg("photo-watermark.jpg");
Console.WriteLine($"logo {logo.Width}x{logo.Height} at {pos}");
photo-grayscale.jpg
photo-sepia.jpg
photo-blur.jpg
photo-sharpen.jpg
photo-brighter.jpg
photo-pixelate.jpg
photo-invert.jpg
photo-vignette.jpg
logo 200x100 at Point [ X=590, Y=390 ]
DrawImage (compositing one image onto another) is part of the core package. drawing.png is created in the drawing section below.
Working with pixels
The indexer image[x, y] is fine for a few pixels but does bounds checks and a lookup per call. For whole-image work use ProcessPixelRows, which gives you each row as a Span<TPixel>:
#:package SixLabors.ImageSharp@4.1.3
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using var image = Image.Load<Rgba32>("photo.jpg");
// slow but simple: indexer
Rgba32 p = image[0, 0];
Console.WriteLine($"top-left pixel: R={p.R} G={p.G} B={p.B} A={p.A} hex={p.ToHex()}");
// fast: process a row at a time as Span<Rgba32>
double sum = 0;
int dark = 0;
image.ProcessPixelRows(accessor =>
{
for (int y = 0; y < accessor.Height; y++)
{
Span<Rgba32> row = accessor.GetRowSpan(y);
foreach (ref Rgba32 px in row)
{
double lum = 0.2126 * px.R + 0.7152 * px.G + 0.0722 * px.B;
sum += lum;
if (lum < 64) dark++;
// keep only the red channel
px.G = 0;
px.B = 0;
}
}
});
long total = (long)image.Width * image.Height;
Console.WriteLine($"average luminance: {sum / total:F1}, dark pixels: {100.0 * dark / total:F1}%");
image.Save("red.png");
// raw bytes out and back in, e.g. to pass to another library
byte[] bytes = new byte[image.Width * image.Height * 4];
image.CopyPixelDataTo(bytes);
Console.WriteLine($"raw RGBA bytes: {bytes.Length:N0}, first pixel: {bytes[0]},{bytes[1]},{bytes[2]},{bytes[3]}");
using var copy = Image.LoadPixelData<Rgba32>(bytes, image.Width, image.Height);
Console.WriteLine($"rebuilt: {copy.Width}x{copy.Height}, same first pixel: {copy[0, 0] == image[0, 0]}");
top-left pixel: R=31 G=31 B=31 A=255 hex=1F1F1FFF
average luminance: 33.9, dark pixels: 82.0%
raw RGBA bytes: 36,879,360, first pixel: 31,0,0,255
rebuilt: 3840x2401, same first pixel: True
foreach (ref Rgba32 px in row) iterates by reference, so assigning px.G changes the image. The span is only valid inside the callback: you can't store it or use it across an await.
Note the memory: a 9-megapixel photo is 37 MB as Rgba32. If you don't need alpha, Rgb24 saves a quarter, and L8 (8-bit grayscale) is one byte per pixel.
CopyPixelDataTo and LoadPixelData move raw pixels to and from other libraries, for example a machine-learning model that expects an RGB byte array.
EXIF metadata and orientation
Phone cameras don't rotate the pixels when you hold the phone sideways. They store the pixels as the sensor saw them and set the EXIF Orientation tag. Browsers honor the tag, but if you resize without it, portrait photos come out lying on their side. AutoOrient() rotates the pixels to match the tag and removes it:
#:package SixLabors.ImageSharp@4.1.3
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Metadata.Profiles.Exif;
using SixLabors.ImageSharp.Processing;
// add EXIF data to a photo, like a phone camera would
using (Image image = Image.Load("photo.jpg"))
{
image.Mutate(x => x.Resize(800, 0));
var exif = new ExifProfile();
exif.SetValue(ExifTag.Make, "Contoso");
exif.SetValue(ExifTag.Model, "Phone 15");
exif.SetValue(ExifTag.DateTimeOriginal, "2026:10:17 09:30:00");
exif.SetValue(ExifTag.Orientation, (ushort)6); // camera held sideways
image.Metadata.ExifProfile = exif;
image.Save("phone.jpg");
}
using (Image image = Image.Load("phone.jpg"))
{
ExifProfile? exif = image.Metadata.ExifProfile;
if (exif is not null)
{
foreach (IExifValue v in exif.Values)
Console.WriteLine($"{v.Tag,-17} = {v.GetValue()}");
if (exif.TryGetValue(ExifTag.Model, out IExifValue<string>? model))
Console.WriteLine($"model: {model.Value}");
}
Console.WriteLine($"stored size: {image.Width}x{image.Height}");
image.Mutate(x => x.AutoOrient());
Console.WriteLine($"after AutoOrient: {image.Width}x{image.Height}, orientation tag: " +
(image.Metadata.ExifProfile!.TryGetValue(ExifTag.Orientation, out var o) ? o.Value : "none"));
}
Orientation = 6
Make = Contoso
Model = Phone 15
DateTimeOriginal = 2026:10:17 09:30:00
model: Phone 15
stored size: 800x500
after AutoOrient: 500x800, orientation tag: none
EXIF often contains GPS coordinates, camera serial numbers and timestamps. Strip it (Metadata.ExifProfile = null, and XmpProfile/IptcProfile too) before publishing images that users upload. Keep the ICC color profile (IccProfile) if colors matter.
Drawing shapes and text
Drawing is in a separate package, SixLabors.ImageSharp.Drawing, which also brings in SixLabors.Fonts. Version 3 draws through a DrawingCanvas obtained from Paint:
#:package SixLabors.ImageSharp@4.1.3
#:package SixLabors.ImageSharp.Drawing@3.1.3
using SixLabors.Fonts;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
FontFamily family = SystemFonts.TryGet("Arial", out var arial)
? arial
: SystemFonts.Families.First();
Font font = family.CreateFont(36, FontStyle.Bold);
using var image = new Image<Rgba32>(600, 300, Color.White.ToPixel<Rgba32>());
image.Mutate(ctx => ctx.Paint(canvas =>
{
canvas.Fill(Brushes.Solid(Color.LightSkyBlue), new Rectangle(20, 20, 200, 120));
canvas.Draw(Pens.Solid(Color.Navy, 4), new Rectangle(20, 20, 200, 120));
canvas.Fill(Brushes.Solid(Color.Orange), new EllipsePolygon(400, 80, 70));
canvas.DrawLine(Pens.Solid(Color.Red, 3), new PointF(20, 170), new PointF(580, 170));
canvas.Fill(Brushes.Solid(Color.SeaGreen),
new Polygon(new PointF[] { new(460, 280), new(520, 190), new(580, 280) }));
var text = new RichTextOptions(font) { Origin = new PointF(20, 200) };
canvas.DrawText(text, "Hello, ImageSharp", Brushes.Solid(Color.Black), pen: null);
}));
image.SaveAsPng("drawing.png");
FontRectangle size = TextMeasurer.MeasureAdvance("Hello, ImageSharp", new TextOptions(font));
Console.WriteLine($"font: {family.Name}, text size: {size.Width:F0}x{size.Height:F0}");
font: Arial, text size: 314x36
The result is a light blue rectangle with a navy border, an orange circle, a red line, a green triangle and bold black text.
SystemFonts reads fonts installed on the machine. Docker images usually have none, so for servers ship a .ttf with the app and load it with new FontCollection().Add("fonts/Inter.ttf"). TextMeasurer tells you how big text will be, so you can center it or shrink the font until it fits.
Older tutorials call ctx.Fill(...) and ctx.DrawText(...) directly on the processing context. That was the Drawing 2.x API.
Processing uploads safely
Image decoders are a classic attack surface. A 50 KB PNG can declare 50000x50000 pixels and try to allocate 10 GB, and an animated GIF can contain thousands of frames. When images come from users:
#:package SixLabors.ImageSharp@4.1.3
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.Formats.Webp;
using SixLabors.ImageSharp.Processing;
const int MaxPixels = 40_000_000; // ~160 MB as Rgba32
string[] allowed = ["JPEG", "PNG", "WEBP", "GIF"];
// stand-in for an uploaded file: a request body, a blob from storage, etc.
byte[] upload = await File.ReadAllBytesAsync("photo.jpg");
Console.WriteLine(await ProcessUploadAsync(new MemoryStream(upload)));
Console.WriteLine(await ProcessUploadAsync(new MemoryStream("GIF89a garbage"u8.ToArray())));
async Task<string> ProcessUploadAsync(Stream input)
{
try
{
// 1. read the header only, reject before allocating pixel memory
ImageInfo info = await Image.IdentifyAsync(input);
string format = info.Metadata.DecodedImageFormat!.Name;
if (!allowed.Contains(format))
return $"rejected: {format} not allowed";
if ((long)info.Width * info.Height > MaxPixels)
return $"rejected: {info.Width}x{info.Height} is too large";
// 2. decode for real; MaxFrames limits work for animated GIF/WebP
input.Position = 0;
var options = new DecoderOptions { MaxFrames = 1 };
using Image image = await Image.LoadAsync(options, input);
image.Mutate(x => x.AutoOrient().Resize(new ResizeOptions
{
Size = new Size(1024, 1024),
Mode = ResizeMode.Max,
}));
image.Metadata.ExifProfile = null;
// 3. re-encode: never serve the uploaded bytes as-is
using var output = new MemoryStream();
await image.SaveAsWebpAsync(output, new WebpEncoder { Quality = 80 });
return $"ok: {format} {info.Width}x{info.Height} -> WebP {image.Width}x{image.Height}, {output.Length:N0} bytes";
}
catch (Exception e) when (e is UnknownImageFormatException or InvalidImageContentException)
{
return $"rejected: {e.GetType().Name}";
}
}
ok: JPEG 3840x2401 -> WebP 1024x640, 33,972 bytes
rejected: InvalidImageContentException
The steps:
IdentifyAsyncchecks format and size from the header. Don't trust the file extension or theContent-Typeheader.MaxFrames = 1decodes only the first frame of animations.- Re-encoding drops anything hidden in the file (scripts in SVG-like payloads, appended ZIP archives, metadata) and guarantees the output is a valid image of the type you claim.
Also limit the request body size in the web framework and decode with a CancellationToken (all async methods accept one) so a slow upload can't tie up the server. Image processing is CPU heavy, so cap how many run concurrently, for example with a SemaphoreSlim. See Async Await.
SkiaSharp
SkiaSharp exposes the Skia API almost one to one: SKBitmap for pixels, SKCanvas for drawing, SKImage for immutable images, SKData for encoded bytes.
#:package SkiaSharp@4.153.1
using SkiaSharp;
// decode, resize, encode
using SKBitmap photo = SKBitmap.Decode("photo.jpg");
Console.WriteLine($"photo: {photo.Width}x{photo.Height} {photo.ColorType}");
int w = 800, h = photo.Height * w / photo.Width;
using SKBitmap small = photo.Resize(new SKImageInfo(w, h), new SKSamplingOptions(SKCubicResampler.Mitchell));
using (SKData data = small.Encode(SKEncodedImageFormat.Jpeg, 80))
using (var fs = File.Create("skia-small.jpg"))
data.SaveTo(fs);
Console.WriteLine($"skia-small.jpg: {w}x{h}, {new FileInfo("skia-small.jpg").Length:N0} bytes");
// draw on a new surface
var info = new SKImageInfo(400, 200);
using SKSurface surface = SKSurface.Create(info);
SKCanvas canvas = surface.Canvas;
canvas.Clear(SKColors.White);
using var fill = new SKPaint { Color = SKColors.Orange, IsAntialias = true };
canvas.DrawCircle(100, 100, 70, fill);
using var font = new SKFont(SKTypeface.FromFamilyName("Arial", SKFontStyle.Bold), 32);
using var textPaint = new SKPaint { Color = SKColors.Black, IsAntialias = true };
canvas.DrawText("Skia", 200, 115, font, textPaint);
using SKImage image = surface.Snapshot();
using SKData png = image.Encode(SKEncodedImageFormat.Png, 100);
File.WriteAllBytes("skia.png", png.ToArray());
Console.WriteLine($"skia.png: {png.Size:N0} bytes");
photo: 3840x2401 Bgra8888
skia-small.jpg: 800x500, 39,703 bytes
skia.png: 5,001 bytes
The SkiaSharp package includes native binaries for Windows and macOS. On Linux also add SkiaSharp.NativeAssets.Linux (or SkiaSharp.NativeAssets.Linux.NoDependencies for slim Docker images without fontconfig). Unlike ImageSharp, SKBitmap.Decode doesn't apply EXIF orientation. Read it with SKCodec.EncodedOrigin and rotate yourself.
Choose SkiaSharp when you need GPU-accelerated rendering, complex vector graphics, PDF output (SKDocument.CreatePdf) or the fastest possible decoding. Choose ImageSharp for simple deployment and an idiomatic C# API.
Tips
- Dispose every image.
Image,SKBitmap,SKImageandSKDataall hold large buffers. Useusing. - Call
IdentifybeforeLoadwhenever you only need the size or format, and to reject huge images. - Use
DecoderOptions.TargetSizefor thumbnails of large JPEGs. It's several times faster. - Call
AutoOrient()before resizing photos, or portrait phone photos come out rotated. - Strip EXIF from images that users upload before publishing them. It can contain their location.
- Prefer
Mutatewhen you don't need the original.Cloneallocates a second full-size buffer. - Use
ProcessPixelRowsfor per-pixel work, not theimage[x, y]indexer in a loop. - Don't use
System.Drawingin new code. It's Windows-only on .NET 6+, and Microsoft doesn't support GDI+ in services such as ASP.NET. - For reading and writing files and streams in general, see File and Stream IO.