Magick.NET
| Language | C# (.NET 8+, .NET Framework 4.7+) |
|---|---|
| License | Apache-2.0 (ImageMagick license for the native part) |
| Repository | github.com/dlemstra/Magick.NET |
| Documentation | Magick.NET docs |
| Depends on | native ImageMagick (included in the NuGet package), which uses libheif with libaom/dav1d for AVIF |
| Read / write | yes / yes |
Magick.NET is the .NET binding of ImageMagick. The NuGet packages include native ImageMagick builds for Windows, Linux and macOS (arm64) with AVIF support, so nothing else needs to be installed. AVIF files go through ImageMagick’s HEIC coder, which uses libheif.
The same API handles 100+ formats, so converting between AVIF and JPEG, PNG or WebP is a matter of the file extension or Format property. Encoding AVIF at default settings is slow; set the speed for large batches.
Installation#
Shell
dotnet add package Magick.NET-Q8-AnyCPU
Q8 uses 8 bits per channel and less memory; use Magick.NET-Q16-AnyCPU to keep 10/12-bit AVIF precision. Platform-specific packages (Magick.NET-Q8-x64, -arm64) are smaller.
Basic usage: convert JPEG to AVIF#
C#
using ImageMagick;
using var image = new MagickImage("photo.jpg");
Console.WriteLine($"{image.Width} x {image.Height}");
image.Quality = 60; // 0..100
image.Write("photo.avif"); // format from the extension
using var back = new MagickImage("photo.avif");
back.Write("photo.png");
How to get AVIF width and height without decoding#
MagickImageInfo reads only the header:
C#
using ImageMagick;
var info = new MagickImageInfo("photo.avif");
Console.WriteLine($"{info.Width} x {info.Height}, {info.Format}");
How to set AVIF encoding speed and chroma subsampling#
ImageMagick reads heic: defines for the AVIF encoder:
C#
using var image = new MagickImage("photo.png");
image.Settings.SetDefine("heic:speed", "6"); // 0 (slowest, smallest) .. 9
image.Settings.SetDefine("heic:chroma", "444"); // 420, 422 or 444
image.Quality = 60;
image.Format = MagickFormat.Avif;
image.Write("photo.avif");
How to resize and save as AVIF to a stream#
C#
using var image = new MagickImage("large.jpg");
image.Resize(new MagickGeometry(800, 800)); // fits inside 800x800, keeps aspect ratio
image.Quality = 55;
image.Strip(); // drop metadata
using var output = new MemoryStream();
image.Write(output, MagickFormat.Avif);
byte[] avif = output.ToArray();
How to check that AVIF is supported#
C#
var avif = MagickFormatInfo.Create(MagickFormat.Avif);
Console.WriteLine($"read: {avif?.SupportsReading}, write: {avif?.SupportsWriting}");
Tips#
- Quality 100 gives lossless AVIF.
- Use
MagickImageCollectionto read all frames of an animated AVIF. - Set
ResourceLimits.Memory,ResourceLimits.WidthandResourceLimits.Heightbefore reading untrusted files.