In this post, we'll explore Meziantou.Framework.Imaging. This package, under MIT license, allows you to read, write, and process images in many formats, such as PNG, JPEG, JPEG XL, WebP, GIF, AVIF, HEIC, and TIFF, with code written entirely in C#.
The overview of the package showed what it can do, with a few samples. This post goes into the details.
Images come from many places: the HEIC photos of a phone, the animated GIF of a chat, the screenshots of a bug report. Handling them often means depending on a native library, whose binaries must match the operating system and the processor, and that may not support every format. This package has no native dependency: the codecs, including the AV1 and HEVC decoders and encoders behind AVIF and HEIC, are written in C#. It is also strict: it never drops an animation, a transparency, or metadata silently when the output format cannot store it. This post covers loading, converting, resizing, metadata, untrusted files, and large images. Typical use cases are:
- Creating thumbnails and previews of uploaded images
- Converting the HEIC and AVIF photos of phones to JPEG or WebP for the web
- Removing the GPS position and the other private data of a photo before publishing it
- Processing images in a container or a Native AOT application, without installing native libraries
- Accepting untrusted files with limits on their size and their number of frames
- Processing very large images and long animations without loading them entirely in memory
#Installation
Shell
dotnet package add Meziantou.Framework.Imaging
The package targets .NET 10 and .NET 11. The images, loading, and processing are in the Meziantou.Framework.Imaging namespace, the encoders and their settings in Meziantou.Framework.Imaging.Formats, and the orientation, EXIF, XMP, and color profiles in Meziantou.Framework.Imaging.Metadata.
#Loading and identifying images
Image.Load decodes an image from a path, a stream, or bytes in memory, and Image.LoadAsync does the same for paths and streams. The format comes from the content of the data, never from the extension of the file, so a PNG file named photo.jpg loads as a PNG image:
C#
using var image = Image.Load("photo.jpg");
Console.WriteLine($"{image.Metadata.SourceFormat} {image.Width}x{image.Height} {image.PixelFormat}");
// Jpeg 1200x900 Rgb24
The image uses the smallest pixel format that keeps the pixels of the file exactly: Rgb24 for most JPEG files, Rgba32 for an image with transparency, or a 16-bit format for a 16-bit PNG file. To work with one pixel format, Image.Load<Rgba32> converts the pixels while loading. Image is disposable, and the image keeps no reference to the file, the stream, or the bytes it was loaded from.
To check an upload, or to get the size of a file without decoding its pixels, use Image.Identify. By default, it reads the headers only, and it returns null for what the headers don't say, instead of guessing. A GIF file doesn't store its number of frames, so ImageIdentifyMode.FullScan walks the whole file to count them:
C#
var info = Image.Identify("animation.gif");
Console.WriteLine($"{info.Format} {info.Width}x{info.Height}, frames: {info.FrameCount?.ToString() ?? "unknown"}");
// Gif 200x200, frames: unknown
info = Image.Identify("animation.gif", new ImageIdentifyOptions { Mode = ImageIdentifyMode.FullScan });
Console.WriteLine($"{info.Format} {info.Width}x{info.Height}, frames: {info.FrameCount}");
// Gif 200x200, frames: 10
#Converting between formats
Converting an image means loading it and saving it in another format. Save(path) selects the encoder from the extension, and you can pass an encoder to choose the format and its settings. Saving to a stream always needs an encoder, since a stream has no extension:
C#
using var image = Image.Load("photo.heic");
image.Save("photo.png"); // The extension selects the encoder, with its default settings
image.Save("photo.jpg", new JpegEncoder { Quality = 85 });
image.Save("photo.webp", new WebPEncoder { Compression = WebPCompression.Lossy, Quality = 80 });
image.Save("photo.avif", new AvifEncoder { Compression = AvifCompression.Lossy, Quality = 60 });
Note that WebP, AVIF, HEIC, JPEG XL, and JPEG 2000 files are lossless by default, which gives large files for photos: set the lossy compression and a quality for them. Besides these formats, the package reads and writes APNG, GIF, TIFF, BMP, TGA, QOI, Netpbm, ICO and CUR, JPEG XL, JPEG 2000, PSD, DDS, KTX 2.0, and a few others listed in the documentation.
JPEG XL has a feature that the other formats don't: a JPEG file can be recompressed to JPEG XL without decoding its pixels. The JPEG XL file stores the DCT coefficients of the JPEG file with a better compression, plus the data needed to rebuild the original file, byte for byte. This is a good fit for an archive of photos: store the smaller JPEG XL files, and rebuild the JPEG files for the clients that don't support JPEG XL:
C#
// The pixels are not decoded: the JPEG XL file holds the DCT coefficients of the JPEG file
JpegXlTranscoder.RecompressJpeg("photo.jpg", "photo.jxl");
// The JPEG XL file is an image like any other, and it gives back the JPEG file, byte for byte
JpegXlTranscoder.ReconstructJpeg("photo.jxl", "rebuilt.jpg");
To encode pixels as JPEG XL, JpegXlEncoder writes lossless or lossy files. A progressive JPEG XL file can also be shown before it is completely downloaded: the reader returned by Image.OpenReader renders the part of the file received so far with ReadFrameRefinementInto, from a coarse image to the final one.
When the output cannot store something the image has, Save throws an UnsupportedImageFeatureException before writing anything, instead of losing it. Each case has a setting that says how to convert it:
C#
using var logo = Image.Load("logo.png"); // A red disc on a transparent background
try
{
logo.Save("logo.jpg");
}
catch (UnsupportedImageFeatureException ex)
{
Console.WriteLine(ex.Message);
// JPEG output has no alpha channel and the pixel (0, 0) is not fully opaque. Set JpegEncoder.BackgroundColor to composite the pixels over an opaque color, or flatten the image explicitly.
}
// Say what the transparent pixels become
logo.Save("logo.jpg", new JpegEncoder { BackgroundColor = new Rgba32(255, 255, 255) });
The same goes for 16-bit images saved to an 8-bit format (AllowBitDepthReduction) and for metadata (MetadataHandling, see below). A file is written to a temporary file next to the destination, and renamed only once it is complete, so a failed conversion doesn't leave a truncated file behind.
Animations are part of the model, not an exception: an image is a list of full frames with their exact durations, and the GIF, APNG, WebP, AVIF, HEIC, and JPEG XL animations load the same way. Resizing an animation resizes every frame, and saving it to a format that stores animations keeps the frames and their durations. A JPEG file stores one picture, so you export the frame you want:
C#
using var animation = Image.Load("animation.gif");
Console.WriteLine($"{animation.Frames.Count} frames, {animation.Frames[0].Metadata.Duration.TotalMilliseconds} ms each");
// 10 frames, 100 ms each
animation.Resize(new ResizeOptions(100, 100)); // Every frame
animation.Save("animation.webp"); // Every frame, with its duration
// A JPEG file stores one picture: export a frame explicitly
animation.Frames[0].Save("first-frame.jpg", new JpegEncoder());
#Resizing and processing images
A thumbnail is the most common task. A camera stores the pixels as its sensor reads them, and the rotation of the photo as metadata. So, a good thumbnail turns the pixels upright, keeps the aspect ratio, and converts the colors to sRGB before removing the metadata:
C#
// A JPEG file is decoded at 1/2, 1/4, or 1/8 of its size, as long as it stays at least as large as the target
using var image = Image.Load("photo.jpg", new ImageDecodeOptions { TargetSize = new Size(200, 200) });
Console.WriteLine($"Decoded: {image.Width}x{image.Height}"); // Decoded: 300x225
// The photo is stored sideways: turn the pixels upright
image.AutoOrient();
Console.WriteLine($"Upright: {image.Width}x{image.Height}"); // Upright: 225x300
// Fit inside 200x200 and keep the aspect ratio
image.Resize(new ResizeOptions(200, 200) { Mode = ResizeMode.Contain, AllowUpscaling = false });
Console.WriteLine($"Thumbnail: {image.Width}x{image.Height}"); // Thumbnail: 150x200
// Viewers assume sRGB for an image without color profile: convert the colors before removing it
image.ConvertColorProfile(IccProfile.Srgb);
image.Save("thumbnail.jpg", new JpegEncoder
{
Quality = 80,
MetadataHandling = MetadataHandling.Strip, // No EXIF, XMP, comments, or color profile
});
TargetSize is what makes this fast for large photos: the JPEG decoder computes a smaller image from fewer samples, instead of decoding millions of pixels to throw most of them away. It also applies to JPEG 2000, still lossy JPEG XL images (at 1/8), interlaced PNG, and TIFF files that store reduced images. The other formats are decoded at full size. AutoOrient matters because the orientation is removed with the rest of the metadata: without it, the thumbnail of a portrait photo would be sideways. The sample photo is labeled with the Display P3 color profile, as the photos of recent phones are, and would look dull once its profile is removed without converting its colors first.
ResizeOptions.Mode says how the image meets the box, and Filter sets the resampling filter. Bicubic is the default; Lanczos, Mitchell-Netravali, box, nearest neighbor, and a few others are available. Colors are filtered with their alpha premultiplied, so the hidden color of transparent pixels doesn't bleed into the visible ones:
C#
using var image = Image.Load("photo.png"); // 1200x900
using var cover = image.Clone();
cover.Resize(new ResizeOptions(200, 200) { Mode = ResizeMode.Cover }); // Fills the box, crops the rest
Console.WriteLine($"{cover.Width}x{cover.Height}"); // 200x200
using var pad = image.Clone();
pad.Resize(new ResizeOptions(200, 200) { Mode = ResizeMode.Pad, BackgroundColor = new Rgba64(0, 0, 0) }); // Letterbox
Console.WriteLine($"{pad.Width}x{pad.Height}"); // 200x200
image.Resize(new ResizeOptions(600, 600) { Filter = ResamplingFilter.Lanczos3 }); // Contain, the default mode
Console.WriteLine($"{image.Width}x{image.Height}"); // 600x450
The processing operations are extension methods that change the image in place, which is why the example clones it first. A geometry change applies to every frame of an animation or, when it fails, leaves the image unchanged:
C#
using var image = Image.Load("photo.png");
image.Crop(new Rectangle(100, 50, 800, 600));
image.Rotate(RotateMode.Rotate90);
image.Flip(FlipMode.Horizontal);
image.Grayscale();
image.GaussianBlur(2);
Console.WriteLine($"{image.Width}x{image.Height} {image.PixelFormat}"); // 600x800 Rgb24
Grayscale changes the colors and keeps the pixel format: use CloneAs<Gray8>() to store the image with one channel. The package has many more operations: sharpening, rotation by any angle, perspective correction, automatic crop of a uniform background, color adjustments, histogram equalization, color reduction to a palette, and image comparison. The documentation lists them all.
#Reading and removing metadata
Image.Metadata holds the orientation, the color profile (ICC), the EXIF and XMP blocks, the resolution, and the text entries, such as the comments of a JPEG file. Decoders report the orientation and the color profile without applying them: only AutoOrient turns the pixels, and only ConvertColorProfile converts the colors. The EXIF and XMP blocks are kept as raw bytes; the library doesn't edit their tags one by one.
C#
using var image = Image.Load("photo.jpg");
var metadata = image.Metadata;
Console.WriteLine(metadata.Orientation); // RightTop
Console.WriteLine(metadata.IccProfile?.ColorSpace); // Rgb
Console.WriteLine(metadata.ExifProfile is not null); // True
Console.WriteLine(string.Join(", ", metadata.TextEntries)); // Comment: Taken by Alice
The EXIF block of a photo can contain the GPS position, the date, and the camera. To publish a photo without them, remove the blocks and keep what changes how the photo looks:
C#
using var image = Image.Load("photo.jpg");
// The orientation is a separate value, which the encoder would write in a new EXIF block: apply it to the pixels
image.AutoOrient();
// EXIF holds the GPS position, the date, and the camera; XMP can hold the same and more
image.Metadata.ExifProfile = null;
image.Metadata.XmpProfile = null;
image.Metadata.TextEntries.Clear();
// The color profile is kept: it only describes the colors
image.Save("published.jpg");
Each format stores different metadata: JPEG, PNG, WebP, AVIF, and HEIC store EXIF, XMP, and ICC profiles. BMP stores only an ICC profile, and QOI, TGA, and Netpbm store none of them. The MetadataHandling property of the encoders decides what happens to the metadata the format cannot store:
MetadataHandling | Writes | When the format cannot store some metadata |
|---|
Strict (default) | Everything the image has | Throws before writing anything |
DiscardUnsupported | What the format can store | Drops the rest |
Strip | No optional metadata | Nothing to drop |
C#
using var image = Image.Load("photo.jpg");
try
{
image.Save("photo.bmp");
}
catch (UnsupportedImageFeatureException ex)
{
Console.WriteLine(ex.Message);
// The Bmp format cannot store the EXIF profile. Remove it, or set the encoder's MetadataHandling to DiscardUnsupported or Strip.
}
// Strip also removes the orientation and the color profile: apply them to the pixels first
image.AutoOrient();
image.ConvertColorProfile(IccProfile.Srgb);
image.Save("photo.bmp", new BmpEncoder { MetadataHandling = MetadataHandling.Strip });
The frame durations and the loop count of an animation are not metadata: no policy removes them.
#Processing untrusted files
A small file can describe a huge image: the header of a PNG file can declare a canvas of 30,000 x 30,000 pixels, and a GIF file can contain thousands of frames. ImageResourceLimits bounds the size of the canvas, the number of pixels and frames, the encoded bytes, the metadata, and the memory an image may allocate. The limits are checked before allocating anything. By default, an image is limited to 32,768 pixels per side, 100 million pixels per frame, 1,000 frames, and 512 MiB of live memory. A service that accepts uploads can lower them:
C#
var configuration = new ImageConfiguration
{
Limits = new ImageResourceLimits { MaxWidth = 4096, MaxHeight = 4096, MaxFrames = 100 },
};
try
{
using var image = Image.Load("upload.png", new ImageDecodeOptions { Configuration = configuration });
}
catch (ImageResourceLimitException ex)
{
Console.WriteLine($"{ex.Kind}: {ex.Requested} > {ex.Limit}"); // Width: 6000 > 4096
}
catch (ImageException)
{
// Not an image, a corrupted file, or a feature the library does not support
}
Each kind of error has its own exception, and they all derive from ImageException: UnknownImageFormatException for data that is not an image, InvalidImageContentException for a corrupted or truncated file, UnsupportedImageFeatureException for a valid feature that the library doesn't support or a conversion that would lose data, and ImageResourceLimitException for an exceeded limit. I/O errors are not wrapped, as they are not a problem of the file.
#Large images with bounded memory
A decoded image takes much more memory than its file: the JPEG file of a scan of 10,000x8,000 pixels is compressed, but its decoded pixels take 240 MB. When you only need a part of it, ImageDecodeOptions.Region decodes a rectangle without decoding the rest. Combined with a memory limit, the application can open such files without risking its memory:
C#
// A scan of 10000x8000 pixels
var configuration = new ImageConfiguration
{
Limits = new ImageResourceLimits { MaxLiveAllocationBytes = 64 * 1024 * 1024 },
};
try
{
using var full = Image.Load("scan.jpg", new ImageDecodeOptions { Configuration = configuration });
}
catch (ImageResourceLimitException ex)
{
Console.WriteLine($"{ex.Kind}: {ex.Requested} > {ex.Limit}"); // LiveAllocationBytes: 241827840 > 67108864
}
// Only the blocks of the area are decoded, within the same limit
using var viewport = Image.Load("scan.jpg", new ImageDecodeOptions
{
Configuration = configuration,
Region = new Rectangle(4000, 3000, 1024, 768),
});
Console.WriteLine($"{viewport.Width}x{viewport.Height}"); // 1024x768
Regions are supported for JPEG, JPEG 2000, TIFF, AVIF, and HEIC files; other formats throw an UnsupportedImageFeatureException. Large scans stored as tiled TIFF files make viewports cheap, as only the tiles the area meets are read. To show the whole image smaller, TargetSize, presented above, decodes a JPEG file at a fraction of its size.
Animations have the same problem in another dimension: Image.Load decodes every frame. The streaming readers and writers handle one frame at a time, so the memory doesn't depend on the length of the animation. They also have asynchronous methods:
C#
await using var reader = await Image.OpenReaderAsync<Rgba32>("long-animation.gif");
var info = reader.Info;
var size = new Size(info.Width / 2, info.Height / 2);
await using var writer = Image.CreateWriter<Rgba32>("long-animation.webp", new ImageWriterOptions(size)
{
Animation = info.Animation, // The play count
Metadata = info.Metadata,
});
// One frame in memory at a time, whatever the length of the animation
while (await reader.ReadFrameAsync() is { } frame)
{
using (frame)
{
frame.Resize(new ResizeOptions(size) { Mode = ResizeMode.Stretch });
await writer.WriteFrameAsync(frame.Frames[0]);
}
}
// Mandatory: disposing a writer that is not completed aborts the output, and the file is not created
await writer.CompleteAsync();
Console.WriteLine(reader.FramesRead); // 30
The Complete call is what makes the output safe: if the processing fails in the middle, the writer is disposed without being completed, and no truncated file is left behind. Some formats write the number of frames before the image data: PNG, AVIF, and HEIC writers need ExpectedFrameCount, while GIF and WebP don't. ReadFrameInto writes the next frame into an image you own, reusing its pixels instead of allocating a new image per frame. Last, the library keeps returned buffers in a pool for the next operations; in a container with little memory, lower ImageBufferPool.MaxRetainedBytes, or set it to 0.
#Additional resources
This post is part of the series 'Exploring Meziantou.Framework'. Be sure to check out the rest of the blog posts of the series!Show the 19 posts of the series
Do you have a question or a suggestion about this post? Contact me!