.NET Image and Video Libraries
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Baseline date: 2026-10-07. Latest stable versions listed on NuGet on that date: SixLabors.ImageSharp 4.1.2, SkiaSharp 4.153.1,
NetVips 3.2.0, BlurHashSharp.SkiaSharp 1.3.4, FFMpegCore 5.5.0 and Xabe.FFmpeg 6.1.1. The snippets below follow the
documented APIs of each library, and were compiled and run on the .NET 10 SDK (mcr.microsoft.com/dotnet/sdk:10.0, Linux
arm64) with SixLabors.ImageSharp 4.1.3, SkiaSharp 3.119.4 and 4.155.0, NetVips 3.2.0 with NetVips.Native 8.18.7,
Blurhash.SkiaSharp 2.0.0, BlurHashSharp.SkiaSharp 1.3.4, BlurHashSharp.ImageSharp 1.3.4 and FFMpegCore 6.0.0, with FFmpeg from
the Debian package. Xabe.FFmpeg 6.1.1 was restored but not exercised, so its snippet follows the documentation. The runs found
several differences between the documented APIs and the current packages, which are corrected below. ImageSharp, SkiaSharp
and FFMpegCore have changed their APIs between major versions, so check the release notes of the version you install.
Image libraries
| Library | Licence | Notes |
|---|---|---|
ImageSharp (SixLabors.ImageSharp) |
Six Labors Split License |
Fully managed code, no native dependencies. JPEG, PNG, GIF, BMP, TIFF and WebP. No AVIF or HEIC. Under the Six Labors Split License a commercial licence is needed above US$1M revenue. Read the license text for the exact terms before you ship it in a product. |
MIT |
Bindings to Google’s Skia, with native assets per platform. JPEG, PNG and WebP encode, plus drawing. Fast and widely used. |
|
MIT |
Bindings to libvips, with the native library in a companion package. The best throughput and the widest format support, including AVIF and HEIC when libvips is built with libheif. |
ImageSharp 4 enforces the licence at build time. A Debug build prints the warning "No Six Labors license found. This Debug build can continue, but Release builds require a valid license", and a Release build fails with the error "No Six Labors license found. Set $(SixLaborsLicenseKey), set $(SixLaborsLicenseFile), or add a 'sixlabors.lic' file to the project/workspace". Plan for the key in your CI before the first release build, not after it.
If the product is closed source and earns more than the ImageSharp threshold, the practical choices are paying for the licence, or using SkiaSharp or NetVips, which are MIT.
ImageSharp
dotnet add package SixLabors.ImageSharp
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.Formats.Webp;
using SixLabors.ImageSharp.Processing;
public static async Task MakeVariantsAsync(string input, string outDir)
{
using var original = await Image.LoadAsync(input);
original.Mutate(x => x.AutoOrient()); // apply EXIF orientation once
original.Metadata.ExifProfile = null; // drop EXIF, including GPS
foreach (var width in new[] { 320, 640, 1280 })
{
if (width >= original.Width) continue; // never upscale
using var copy = original.Clone(x => x.Resize(new ResizeOptions { Size = new Size(width, 0), Mode = ResizeMode.Max }));
await copy.SaveAsync($"{outDir}/w{width}.webp", new WebpEncoder { Quality = 78 });
await copy.SaveAsync($"{outDir}/w{width}.jpg", new JpegEncoder { Quality = 80 });
}
}
ResizeMode.Max fits the image inside the box and also enlarges: the first version of this example, which resized to every
width, turned a 1080 pixel wide photo into a 1280 by 2276 one. The guard avoids that and the single AutoOrient avoids
decoding the file three times. The Size(width, 0) form keeps the aspect ratio.
Reference: ImageSharp documentation.
SkiaSharp
using SkiaSharp;
public static void MakeWebp(string input, string output, int width)
{
using var original = SKBitmap.Decode(input);
var height = (int)Math.Round(original.Height * (double)width / original.Width);
using var resized = original.Resize(new SKImageInfo(width, height), new SKSamplingOptions(SKFilterMode.Linear, SKMipmapMode.Linear));
using var image = SKImage.FromBitmap(resized);
using var data = image.Encode(SKEncodedImageFormat.Webp, 78);
using var stream = File.OpenWrite(output);
data.SaveTo(stream);
}
SkiaSharp does not apply EXIF orientation automatically for bitmaps: with a phone photo whose tag says to rotate, SKBitmap.Decode
returned 1920 by 1080 pixels where the upright picture is 1080 by 1920, and SKCodec.EncodedOrigin reported RightTop. Use
SKCodec.EncodedOrigin to find the rotation and
draw the bitmap on a rotated canvas. Reference: SkiaSharp API documentation.
NetVips
dotnet add package NetVips
dotnet add package NetVips.Native
using NetVips;
// Thumbnail() shrinks on load, so it is much cheaper than load-then-resize.
using var image = Image.Thumbnail("original.jpg", 640, height: 1_000_000, size: Enums.Size.Down);
// keep: ForeignKeep.None strips all metadata (libvips 8.15 replaced the old strip option with keep).
image.Webpsave("w640.webp", q: 78, keep: Enums.ForeignKeep.None);
image.Heifsave("w640.avif", q: 60, compression: Enums.ForeignHeifCompression.Av1, keep: Enums.ForeignKeep.None);
Thumbnail fits the image into a box of width by height, and the height defaults to the width. For a portrait photo of
1080 by 1920 pixels, Thumbnail(file, 640) therefore returned 360 by 640, and passing a very large height as above
returned the 640 by 1138 that a width-only variant should have. Thumbnail also applies the EXIF orientation, so the upright
size is what you get. Reference: NetVips documentation and the
libvips API.
BlurHash in .NET
| Package | Notes |
|---|---|
Blurhash.ImageSharp, Blurhash.SkiaSharp and Blurhash.Core (blurhash.net) |
Encoder and decoder with one package per imaging library. Pick the one that matches your image library. |
Encoder only. |
using Blurhash.SkiaSharp;
using SkiaSharp;
using var bitmap = SKBitmap.Decode("original.jpg");
using var small = bitmap.Resize(new SKImageInfo(64, 64), new SKSamplingOptions(SKFilterMode.Linear, SKMipmapMode.Linear));
string hash = Blurhasher.Encode(small, 4, 3); // 4 x 3 components, 28 characters
Blurhash.SkiaSharp 2.0.0 (the blurhash.net family) ran against SkiaSharp 4.155 and printed a 28 character hash for the phone
photo of the examples (Blurhasher is a static class, so there is no encoder instance to create). With SkiaSharp 2.88.x
the BlurHashSharp.SkiaSharp call BlurHashEncoder.Encode(4, 3, stream) also worked and printed 28 characters. Both
snippets decode with the orientation ignored, so apply the rotation first when the BlurHash must match the upright picture.
Resize to about 64 pixels before encoding when your library lets you, see the BlurHash page.
Video libraries
| Library | Licence | Notes |
|---|---|---|
MIT |
.NET wrapper over the ffmpeg and ffprobe executables, with a fluent argument builder and helpers for snapshots. |
|
Non-commercial licence |
Free for non-commercial use. Commercial use needs a paid licence, so check the terms before you use it in a product. |
Both need FFmpeg and FFprobe installed (or downloaded at startup) and accessible to the process.
FFMpegCore: probe, transcode and snapshot
dotnet add package FFMpegCore
using FFMpegCore;
using FFMpegCore.Enums;
using System.Drawing;
GlobalFFOptions.Configure(new FFOptions { BinaryFolder = "/usr/bin" });
var info = await FFProbe.AnalyseAsync("input.mov"); // reject unreasonable input first
var duration = info.Duration;
await FFMpegArguments
.FromFileInput("input.mov")
.OutputToFile("720p.mp4", overwrite: true, options => options
.WithVideoCodec(VideoCodec.LibX264)
.WithConstantRateFactor(22)
.WithAudioCodec(AudioCodec.Aac)
.WithVideoFilters(filter => filter.Scale(-2, 720))
.WithFastStart())
.ProcessAsynchronously();
await FFMpeg.Snapshot("input.mov", "cover.jpg", new Size(720, -1), TimeSpan.FromSeconds(duration.TotalSeconds * 0.1))
.ProcessAsynchronously();
This follows the examples in the FFMpegCore README. System.Drawing
Size is used by the snapshot helper (qualify it when the file also imports ImageSharp, which has its own Size), and
FFMpegCore.Extensions.SkiaSharp offers an in-memory variant. Run against FFMpegCore 6.0.0, the transcode produced a 1280
by 720 file and the snapshot a 720 by 405 JPEG. In that version FFMpeg.Snapshot returns an argument processor and does
nothing until you call ProcessAsynchronously() or ProcessSynchronously(): a call whose result is dropped, as in older
examples, returns without error and writes no file.
Xabe.FFmpeg
using Xabe.FFmpeg;
FFmpeg.SetExecutablesPath("/usr/bin");
IMediaInfo info = await FFmpeg.GetMediaInfo("input.mov");
IVideoStream video = info.VideoStreams.First()!.SetCodec(VideoCodec.h264).SetSize(VideoSize.Hd720);
IConversion conversion = FFmpeg.Conversions.New().AddStream(video).AddStream(info.AudioStreams.First()!)
.SetOutput("720p.mp4");
await conversion.Start();
Reference: Xabe.FFmpeg. For fine control of the encoder options, give FFmpeg the argument list directly
(AddParameter).
Worked example: the Bookshelf cover and trailer on .NET
The running example is the Bookshelf upload: a phone photo of a book cover and the trailer video. The photo is 1920 by 1080 pixels with an EXIF tag that says to rotate it to 1080 by 1920, and the trailer is the 20 second 1080p clip of encoding fundamentals. One console program ran every library above on them, and the observable differences decide which library fits:
| Library and call | What it did with the phone photo |
|---|---|
ImageSharp with the corrected |
Upright source 1080 by 1920. Variants of 320 by 569 and 640 by 1138, and no 1280 variant because the upright width is only 1080. |
SkiaSharp |
1920 by 1080, orientation ignored, |
NetVips |
640 by 1138, orientation applied. Without the height argument, 360 by 640. |
NetVips |
WebP of 9.4 KB and AVIF of 6.3 KB at 640 pixels wide, quality 78 and 60 respectively. AVIF worked because the NetVips.Native package bundles a libvips with libheif. |
A ladder with FFMpegCore
The video side uses the same ladder as the other language pages: probe the file, keep the rungs that do not upscale, and encode each rung without audio with a capped CRF and a keyframe every two seconds, with a progress callback and a time limit. Against FFMpegCore 6.0.0 the code is:
// Ladder with FFMpegCore: probe, never upscale, progress and a time limit
var rungs = new[] { (Name: "1080p", Height: 1080, Crf: 22, MaxK: 6000), (Name: "720p", Height: 720, Crf: 22, MaxK: 3000), (Name: "360p", Height: 360, Crf: 23, MaxK: 800) };
var source = await FFProbe.AnalyseAsync("/dn/in/trailer.mp4");
foreach (var rung in rungs.Where(r => r.Height <= source.PrimaryVideoStream!.Height))
{
var shown = -1;
using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(30));
await FFMpegArguments.FromFileInput("/dn/in/trailer.mp4")
.OutputToFile($"{outDir}/ladder-{rung.Name}.mp4", overwrite: true, options => options
.WithVideoCodec(VideoCodec.LibX264)
.WithConstantRateFactor(rung.Crf)
.WithVideoFilters(filter => filter.Scale(-2, rung.Height))
.WithCustomArgument($"-an -preset veryfast -maxrate {rung.MaxK}k -bufsize {rung.MaxK * 2}k -g 48 -keyint_min 48 -sc_threshold 0 -pix_fmt yuv420p")
.WithFastStart())
.NotifyOnProgress((TimeSpan done) => { var p = done / source.Duration * 100; var step = (int)p / 50; if (step != shown) { shown = step; Console.WriteLine($"{rung.Name} {p:0}%"); } })
.CancellableThrough(cts.Token)
.ProcessAsynchronously();
var made = await FFProbe.AnalyseAsync($"{outDir}/ladder-{rung.Name}.mp4");
Console.WriteLine($"{rung.Name}: {made.PrimaryVideoStream!.Width}x{made.PrimaryVideoStream.Height} {made.PrimaryVideoStream.BitRate / 1000} kbit/s");
}
The loop printed the progress of each rung and then the probe of the result: 1920 by 1080 at 5.7 Mbit/s, 1280 by 720 at 2.1
Mbit/s and 640 by 360 at 0.4 Mbit/s (the veryfast preset of the example gives somewhat lower rates than the slow preset of the
encoding page). Three API details came out of running it, all different from older FFMpegCore examples: the progress
overload that takes the total duration is gone, so NotifyOnProgress receives the elapsed TimeSpan and the percentage is
done / source.Duration; options that the fluent builder does not expose (here -an, the preset and the rate cap) go in
WithCustomArgument; and a CancellationToken created from a CancellationTokenSource with a timeout is passed to
CancellableThrough, which kills the FFmpeg process when it fires. Packaging the rungs as HLS and DASH is a second step with
FFmpeg or a packager, see video streaming.
ASP.NET Core upload endpoint with BackgroundService and Channel
For small workloads in one process, a bounded Channel<T> read by a BackgroundService is a simple in-memory queue.
It is lost when the process restarts, so it is suited to images that can be regenerated, not to the only copy of a job.
using System.Threading.Channels;
public record ProcessMedia(Guid Id, string Path);
public sealed class MediaQueue
{
private readonly Channel<ProcessMedia> _channel = Channel.CreateBounded<ProcessMedia>(100);
public ValueTask EnqueueAsync(ProcessMedia job) => _channel.Writer.WriteAsync(job);
public IAsyncEnumerable<ProcessMedia> ReadAllAsync(CancellationToken ct) => _channel.Reader.ReadAllAsync(ct);
}
public sealed class MediaWorker(MediaQueue queue, IServiceScopeFactory scopes, ILogger<MediaWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await foreach (var job in queue.ReadAllAsync(stoppingToken))
{
try
{
using var scope = scopes.CreateScope();
var processor = scope.ServiceProvider.GetRequiredService<IMediaProcessor>();
await processor.ProcessAsync(job, stoppingToken); // idempotent: skip if already READY
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogError(ex, "Media job {Id} failed", job.Id);
}
}
}
}
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<MediaQueue>();
builder.Services.AddHostedService<MediaWorker>();
builder.Services.AddScoped<IMediaProcessor, MediaProcessor>();
builder.WebHost.ConfigureKestrel(o => o.Limits.MaxRequestBodySize = 10 * 1024 * 1024);
var app = builder.Build();
app.MapPost("/images", async (IFormFile file, MediaQueue queue) =>
{
if (file.Length is 0 or > 10 * 1024 * 1024)
return Results.BadRequest("Invalid size");
var id = Guid.NewGuid();
var path = Path.Combine(Path.GetTempPath(), id.ToString());
await using (var stream = File.Create(path))
await file.CopyToAsync(stream);
await queue.EnqueueAsync(new ProcessMedia(id, path));
return Results.Accepted($"/images/{id}", new { id, status = "queued" });
}).DisableAntiforgery();
app.Run();
Reference: Background tasks with hosted services in ASP.NET Core
and System.Threading.Channels. IFormFile binding in minimal
APIs requires DisableAntiforgery() for a public API in .NET 8 and later. Keep the CSRF decision explicit for your own
authentication model.
The missing parts, and a run
The endpoint above names IMediaProcessor and returns a status URL, so it needs a processor and a status endpoint. The pieces
below were added to the same program and run in the SDK container with curl:
public enum MediaState { Queued, Processing, Ready, Failed }
public record MediaStatus(Guid Id, MediaState State, string? Blurhash = null, string[]? Variants = null, string? Error = null);
public sealed class MediaStore
{
private readonly ConcurrentDictionary<Guid, MediaStatus> _items = new();
public void Set(MediaStatus status) => _items[status.Id] = status;
public MediaStatus? Get(Guid id) => _items.TryGetValue(id, out var s) ? s : null;
}
public interface IMediaProcessor { Task ProcessAsync(ProcessMedia job, CancellationToken ct); }
public sealed class MediaProcessor(MediaStore store) : IMediaProcessor
{
public Task ProcessAsync(ProcessMedia job, CancellationToken ct)
{
if (store.Get(job.Id)?.State == MediaState.Ready) return Task.CompletedTask; // idempotent
store.Set(new MediaStatus(job.Id, MediaState.Processing));
var outDir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "media-out", job.Id.ToString());
Directory.CreateDirectory(outDir);
var variants = new List<string>();
foreach (var width in new[] { 320, 640, 1280 })
{
using var image = NetVips.Image.Thumbnail(job.Path, width, height: 1_000_000, size: NetVips.Enums.Size.Down); // width only, never upscales
var target = System.IO.Path.Combine(outDir, $"w{image.Width}.webp");
image.Webpsave(target, q: 78, keep: NetVips.Enums.ForeignKeep.None);
variants.Add(System.IO.Path.GetFileName(target));
}
using var bitmap = SkiaSharp.SKBitmap.Decode(job.Path);
using var small = bitmap.Resize(new SkiaSharp.SKImageInfo(64, 64), new SkiaSharp.SKSamplingOptions(SkiaSharp.SKFilterMode.Linear, SkiaSharp.SKMipmapMode.Linear));
var hash = Blurhash.SkiaSharp.Blurhasher.Encode(small, 4, 3);
store.Set(new MediaStatus(job.Id, MediaState.Ready, hash, variants.Distinct().ToArray()));
return Task.CompletedTask;
}
}
and the status endpoint next to MapPost, plus store.Set(new MediaStatus(job.Id, MediaState.Failed, Error: ex.GetType().Name))
in the catch block of the worker and store.Set(new MediaStatus(id, MediaState.Queued)) in the upload handler:
app.MapGet("/images/{id:guid}", (Guid id, MediaStore store) =>
store.Get(id) is { } s ? Results.Ok(s) : Results.NotFound());
The results: the upload of the 1080 by 1920 JPEG returned 202 Accepted with a Location header and, two seconds later, the
status contained the BlurHash and the variants w320.webp, w640.webp and w1080.webp, the last named after the real width
because Size.Down refuses to enlarge a 1080 pixel image to 1280. An upload of random bytes ended in the Failed state
with the error VipsException and a logged stack trace, an empty file returned 400 and an 11 MB file 413. The status
serialises State as a number (2 for Ready) unless you register a JsonStringEnumConverter in the JSON options, so decide
that before clients depend on it.
A queue-backed alternative
When jobs must survive restarts, scale across instances or be retried, replace the channel with a broker and keep the same processor:
-
Azure Service Bus or Storage Queues with the Azure SDK, see the Azure page.
-
Amazon SQS with the AWS SDK for .NET, see the AWS pipeline.
-
RabbitMQ or Kafka with the official clients, see messaging.
-
A library such as Hangfire or Quartz.NET for persisted background jobs, see scheduling.
Publish a job from the endpoint, run a worker as a separate deployment, and give it the idempotency, retry and dead-letter settings described in upload pipelines.
Related pages
-
Video Encoding Fundamentals and Video Streaming: HLS, DASH and CMAF for the ladder and the packaging
-
BlurHash: The Algorithm for what the hash contains
-
Media Optimization for the web and Media Optimization in apps