Magick.NET
| Language | C# (.NET 8+, .NET Framework 4.6.2+) |
|---|---|
| License | Apache 2.0 (ImageMagick license, libwebp BSD-3-Clause) |
| Repository | github.com/dlemstra/Magick.NET |
| Documentation | Magick.NET docs |
| Depends on | bundled native ImageMagick with libwebp (Windows, Linux, macOS; x64 and arm64) |
| Read / write | yes / yes, lossy, lossless, alpha, animation, metadata |
Magick.NET packages ImageMagick and its delegate libraries, including libwebp, in one NuGet package. It converts between WebP and 100+ other formats and exposes all libwebp encoder settings through WebPWriteDefines. Animated WebP is read and written as a MagickImageCollection.
Pick a package by quantum depth: Q8 is enough for WebP (8 bits per channel) and uses half the memory of Q16.
Installation#
Shell
dotnet add package Magick.NET-Q8-AnyCPU
Basic usage: convert to WebP#
C#
using ImageMagick;
using var image = new MagickImage("photo.jpg");
Console.WriteLine($"{image.Width} x {image.Height}");
image.Resize(1200, 0); // 0 keeps the aspect ratio
image.Quality = 80; // WebP quality 0-100
image.Write("photo.webp", MagickFormat.WebP);
Reading works the same: new MagickImage("in.webp"), then Write("out.png").
How to write a lossless WebP with libwebp options#
C#
using ImageMagick;
using ImageMagick.Formats;
using var image = new MagickImage("logo.png");
image.Write("logo.webp", new WebPWriteDefines
{
Lossless = true,
Method = 6, // 0 = fast .. 6 = smallest
Exact = true, // keep RGB values under transparent pixels
});
For lossy files with a separate alpha quality: new WebPWriteDefines { AlphaQuality = 50, UseSharpYuv = true } plus image.Quality = 80.
How to get WebP dimensions without decoding#
C#
var info = new MagickImageInfo("in.webp"); // reads only the header
Console.WriteLine($"{info.Format}: {info.Width} x {info.Height}");
How to convert an animated GIF to animated WebP#
C#
using var frames = new MagickImageCollection("anim.gif");
frames.Coalesce(); // turn partial GIF frames into full frames
foreach (var frame in frames)
frame.Quality = 75;
frames.Write("anim.webp", MagickFormat.WebP);
Console.WriteLine($"{frames.Count} frames, delay of first: {frames[0].AnimationDelay} (1/100 s)");
How to read Exif and ICC metadata from a WebP#
C#
using var image = new MagickImage("in.webp");
IExifProfile? exif = image.GetExifProfile();
if (exif != null)
foreach (IExifValue value in exif.Values)
Console.WriteLine($"{value.Tag}: {value}");
IColorProfile? icc = image.GetColorProfile();
Console.WriteLine(icc?.Description ?? "no ICC profile");
Tips#
image.Strip()removes Exif, XMP and ICC data before writing to make files smaller.- Set
ResourceLimits.MemoryandResourceLimits.Width/Heightwhen processing untrusted uploads.