JPEG XL
editJPEG XL stores lossless and lossy images and animations, with integer or floating-point samples. The library reads every JPEG XL file that does not use the features listed in Limitations, and JpegXlEncoder writes lossless files by default. JpegXlTranscoder stores a JPEG file in a smaller JPEG XL file without any loss, and rebuilds it.
Interoperability does not imply encoder parity with libjxl: the managed encoder makes its own coding decisions. There is no general guarantee of comparable file size, encoding speed or perceptual quality, and equal quality/effort numbers do not establish a matched comparison. Measure representative images at matched decoded quality for lossy output.
What is read and written
| Reading | Writing | |
|---|---|---|
| Coding | Lossy (VarDCT) and lossless (Modular) frames; recompressed JPEG files | Lossless (default) or lossy |
| Samples | Integers up to 24 bits and floating-point numbers, gray and color, alpha; CMYK, converted to RGB | Every pixel format at its own depth (Gray8, Gray16, Rgb24, Rgba32, Bgra32, Rgba64), lossless alpha |
| Animations | Composited into full frames with exact durations and the play count | Full frames, or the regions that change; durations in milliseconds, play count |
| Layers | Composited into the image; JpegXlLayeredImage reads the layers of a still image | Layers of any size and position, with the blend modes of the format and names (JpegXlLayeredImage) |
| Progressive | Renderings of a partial file | Progressive files on request |
| Metadata | ICC profile, EXIF, XMP, enumerated color encodings, orientation | The same |
| Reduced size | 1/8 of the size, for a still lossy image without alpha | - |
8-bit files load as Gray8, Rgb24 or Rgba32; files of up to 16 bits as Gray16, Rgb48 or Rgba64. The orientation of the image header is reported in Metadata.Orientation, never applied.
Read floating-point and CMYK files
JPEG XL also stores the samples of high dynamic range and print workflows. They load without losing anything, or not at all:
- Floating-point samples load as RgbaHalf when every sample is a half-precision number, otherwise as RgbaFloat; a gray image loads as GrayHalf, LaHalf, GrayFloat or LaFloat. Values above 1 (highlights) and below 0 are kept, in the color encoding the file declares (often linear sRGB): nothing is clamped or tone mapped.
- Integer samples of 17 to 24 bits load as RgbaFloat (GrayFloat or LaFloat for a gray image): each sample divided by the largest value, which gives the sample back when multiplied by it. Integers of more than 24 bits do not fit a single-precision number and throw an UnsupportedImageFeatureException.
- A CMYK file (cyan, magenta and yellow in the color channels, black in an extra channel) loads only with ImageDecodeOptions.CmykConversion: its inks are converted from its CMYK profile to RGB, its layers composited first, and the alpha channel is kept. Image.Identify reports ImageColorModel.Cmyk. See Color management.
public static string DescribeJpegXl(string path)
{
var info = Image.Identify(path);
// A CMYK file (ImageColorModel.Cmyk: a black extra channel) is only loaded with a color conversion, here to sRGB
// from the CMYK profile of the file; the other files ignore the option
using var image = Image.Load(path, new ImageDecodeOptions { CmykConversion = CmykConversionOptions.Default });
// Floating-point samples, and integer samples of 17 to 24 bits, load as RgbaHalf or RgbaFloat: values above 1
// (highlights) and below 0 are kept, in the color encoding of the file (Metadata.TransferFunction, Cicp, IccProfile)
return $"{info.ColorModel}, {info.BitsPerComponent} bits: {image.PixelFormat}";
}Layers (frames without duration) are composited with the frames they belong to, with the blend modes and the reference frames of the file: an image holds what a viewer shows. To read the layers themselves, see Write and read layers.
Save a JPEG XL file
public static string SaveJpegXl(string inputPath, string jxlPath, string lossyPath, string animatedPath, string animatedJxlPath)
{
using (var image = Image.Load(inputPath))
{
// Lossless by default: every pixel format is stored as it is (no bit depth reduction, no flattening, and the
// colors of fully transparent pixels are kept). The effort changes the size and the encoding time, never the pixels.
image.Save(jxlPath, new JpegXlEncoder { Effort = 7 });
// Lossy on request: the quality sets the quantization, and the alpha channel stays exact. A progressive file
// can be shown before it is complete.
image.Save(lossyPath, new JpegXlEncoder { Compression = JpegXlCompression.Lossy, Quality = 90, Progressive = true });
}
// Frames are written as they come: the destination does not need to be seekable, whatever the frame count.
using (var animation = Image.Load(animatedPath))
{
animation.Save(animatedJxlPath);
}
// Lossy (VarDCT) and lossless (Modular) files are decoded, whatever wrote them.
var info = Image.Identify(jxlPath);
return $"{info.Format} {info.Size.Width}x{info.Size.Height} {info.PixelFormat}, {info.BitsPerComponent} bits";
}Lossless output keeps every sample, 16-bit samples and the colors of fully transparent pixels included. Lossy output keeps the alpha channel lossless. Unlike AVIF and HEIC, an animation does not need a seekable destination, and unlike WebP it is not kept in memory for a non-seekable one: frames are written as they come, whatever their number.
Write and read layers
A still JPEG XL image can be made of layers, like a document of an image editor: each layer is an image of any size at a position on the canvas, combined with the layers below it, and has an optional name. Viewers show the image the layers make. JpegXlLayeredImage writes such a file and reads its layers back:
public static string SaveJpegXlLayers(string photoPath, string logoPath, string layeredPath)
{
using (var photo = Image.Load<Rgba32>(photoPath))
using (var logo = Image.Load<Rgba32>(logoPath))
using (var document = new JpegXlLayeredImage(photo.Width, photo.Height))
{
// Each layer is an image of any size at a position on the canvas, combined with the layers below it by a blend
// mode of the format: Blend draws the logo over the photo, weighted by its alpha. The layers have the same
// pixel format; the colors of the document describe all of them.
document.AddLayer(photo, name: "Photo");
document.AddLayer(logo, new Point(photo.Width - logo.Width - 8, 8), JpegXlBlendMode.Blend, "Logo");
document.Save(layeredPath, new JpegXlEncoder { Effort = 7 });
}
// Image.Load gives the image the layers make, as a viewer shows it; JpegXlLayeredImage.Load gives the layers back,
// exactly for lossless output, from any still JPEG XL file whose frames are layers
using var layers = JpegXlLayeredImage.Load(layeredPath);
return string.Join(", ", layers.Layers.Select(layer => $"{layer.Name} {layer.Image.Width}x{layer.Image.Height} at {layer.Offset.X},{layer.Offset.Y} ({layer.BlendMode})"));
}- AddLayer copies the image; the layered image owns the copies and disposes them. A layer may start at a negative offset or extend beyond the canvas: the part outside is not shown.
- JpegXlBlendMode has the modes of the format: Replace, Add, Blend (drawn over the layers below, weighted by its alpha), AlphaWeightedAdd and Multiply. The color and alpha channels use the same mode. Below the first layer, the canvas is transparent black.
- Save takes the settings of a JpegXlEncoder: lossless by default, lossy or progressive on request. The layers must have the same pixel format, and Metadata (the color profile, orientation, EXIF and XMP) describes all of them: a layer labeled with other colors is rejected.
- Load reads the layers of any still JPEG XL file whose frames are layers, whatever wrote it; a file of one frame has one layer. Lossless layers come back exactly. An animation, or a file whose frames are blended in a way a list of layers cannot describe (with another reference frame than the layers below, or the alpha channel otherwise than the colors), throws an UnsupportedImageFeatureException.
The decoders blend the layers in floating point, so a 16-bit pixel of a blended layer can differ by one unit between two decoders. An ImageCollection holds pages and icon sizes, never layers: its entries are not blended.
Write smaller animations
OptimizeFrames writes each frame after the first one as the rectangle that changes, drawn over the previous frame. Screen recordings and animations of small moving objects get much smaller; lossless frames still decode exactly:
public static long SaveOptimizedJpegXlAnimation(string animationPath, string jxlPath)
{
using var animation = Image.Load(animationPath);
// Each frame after the first one stores the rectangle that changes, drawn over the previous frame: a screen
// recording or a small moving object costs far less than full frames, and lossless frames decode exactly
animation.Save(jxlPath, new JpegXlEncoder { OptimizeFrames = true });
return new FileInfo(jxlPath).Length;
}Options
| Option | What it does | Default |
|---|---|---|
| Compression | Lossless or Lossy | Lossless |
| Quality | 0 (smallest) to 100 (best) for lossy output: 90 is barely distinguishable from the source, 100 is still lossy | 75 |
| Effort | 0 (fastest, largest) to 9 (slowest, smallest): changes the decisions of the encoder, never lossless pixels nor the size Quality aims at | 5 |
| Progressive | Writes a file that a reader can show at a lower resolution before it is complete; the file is larger | false |
| OptimizeFrames | Writes the frames of an animation after the first one as the rectangle that changes | false |
| DurationRounding | RoundToNearest rounds durations to the nearest millisecond; RequireExact throws | RoundToNearest |
| MetadataHandling | What to do with metadata JPEG XL cannot store (text, resolution) | Strict |
For lossless output, the effort sets how much the encoder learns about the image before coding it. On a 2048x1536 photograph, on one thread of a desktop x64 processor: efforts 0 to 2 take about 80 ms, effort 3 about 340 ms, effort 5 (the default) about 660 ms, effort 7 about 1.4 s and effort 9 about 2.5 s. The file of effort 3 is 23% smaller than the one of efforts 0 to 2, effort 5 is 3% smaller than effort 3, and effort 9 another 2%. Screenshots and graphics gain more from efforts 3 to 5, which code them with a palette of their colors and copy their repeated runs: a 2048x2048 screenshot is about half as large at effort 5 as at effort 4.
For lossy output, from effort 3 the encoder also learns how to code the low-frequency image and the description of the blocks, as it does for lossless output. On 1024x1024 photographs this makes the files 4% smaller at the same quality (7% at quality 30, 2% at quality 90), and 1% on 356x356 ones, for about 15% more encoding time (25% on the small images).
Show an image while it downloads
ReadFrameRefinementInto renders a frame from the bytes received so far: coarse at first, then finer, then the frame itself. A file that is not progressive, or another format, gives the frame at once:
public static int ShowWhileReading(Stream input, Action<Image<Rgba32>, FrameRefinement> show)
{
using var reader = Image.OpenReader<Rgba32>(input);
using var image = new Image<Rgba32>(reader.Info.Width, reader.Info.Height);
var renderings = 0;
// Each call writes a full image: coarse at first (Downsampling 8, then 4, 2), then the frame itself (IsFinal).
// A file that is not progressive, or another format, gives its frame at once. An input that ends early gives the
// renderings it has, then throws: truncation is never a clean end.
while (reader.ReadFrameRefinementInto(image) is { } refinement)
{
show(image, refinement);
renderings++;
if (refinement.IsFinal)
break;
}
return renderings;
}See Show an image while it downloads for the other formats and for partial downloads.
Decode a thumbnail
A lossy frame stores an image at 1/8 of its size before its details: its LF image, one value per block of 8x8 pixels. ImageDecodeOptions.TargetSize and ScaleDenominator = 8 decode that image alone, without reading the details, for a thumbnail of a large photo at a fraction of the memory and the time of a full decode:
- Each pixel is the LF value of its block, which is close to the mean of its pixels. On the right and bottom edges, a block that is not whole also covers the pixels the encoder added to complete it, so an image of a few pixels can differ more.
- Only a still image of one lossy (VarDCT) frame without alpha or other extra channels, without patches, splines, noise or subsampled chrominance is reduced: other files are decoded at full size for a target size, and an exact scale throws an UnsupportedImageFeatureException. So does a scale other than 1/8.
- Readers (ImageReaderOptions) decode at full resolution.
Recompress JPEG files without loss
JpegXlTranscoder.RecompressJpeg stores the coefficients of a JPEG file in a JPEG XL file without decoding its pixels, and TryReconstructJpeg gives the JPEG file back, byte for byte. This is not Image.Save, which stores pixels:
public static bool RecompressJpeg(string jpegPath, string jxlPath, string rebuiltPath)
{
// No pixel is decoded: the JPEG XL file holds the coefficients of the JPEG file. A file that cannot be stored
// exactly (four components, a sampling factor of 4, arithmetic coding) throws; nothing is approximated.
JpegXlTranscoder.RecompressJpeg(jpegPath, jxlPath);
// The file is an image like any other...
using (var image = Image.Load(jxlPath))
{
_ = image.PixelFormat;
}
// ...and gives the JPEG file back, byte for byte. A JPEG XL file made from pixels returns false.
return JpegXlTranscoder.TryReconstructJpeg(jxlPath, rebuiltPath)
&& File.ReadAllBytes(jpegPath).AsSpan().SequenceEqual(File.ReadAllBytes(rebuiltPath));
}- HasJpegReconstructionData tells whether a JPEG XL file holds a JPEG file, without decoding it. TryReconstructJpeg returns
falsefor a file made from pixels, and ReconstructJpeg throws for it. - Files that a JPEG XL frame cannot hold exactly are rejected with an UnsupportedImageFeatureException: CMYK and YCCK files, 4:1:1 sampling, arithmetic-coded, lossless, hierarchical and 12-bit files, among others. Nothing is approximated.
- The recompressed files are read by other JPEG XL decoders, and the library rebuilds the files that
cjxl --lossless_jpeg=1writes. - Since libjxl 0.13,
cjxllets decoders smooth the low-frequency image of a recompressed file, which reduces banding in its pixels: by default when the chroma is not subsampled, and with--jpeg_reconstruction_lfs=1otherwise. Image.Load decodes these files as libjxl 0.13 and jxl-oxide do, and the JPEG file is still rebuilt byte for byte: the smoothing changes the pixels, not the coefficients. JpegXlTranscoder itself writes files without smoothing, whose pixels are the ones of the JPEG file.
Pitfalls
- A frame of an animation without duration is rejected: JPEG XL defines it as a layer of the next frame. Write layers with JpegXlLayeredImage, as a still image.
- Lossy output converts the samples to the XYB color space, which needs an enumerated color encoding (sRGB, linear, BT.709 or DCI, with sRGB, Display P3 or BT.2020 primaries) or an sRGB ICC profile. Another ICC profile, or the PQ and HLG transfer functions, throws an UnsupportedImageFeatureException: write those images losslessly.
- The decoder rejects integer samples of more than 24 bits and premultiplied alpha. A CMYK image throws an UnsupportedImageFeatureException unless the load sets CmykConversion.
- A floating-point image is not saved as JPEG XL as it is: the encoder takes integer pixel formats. Set FloatingPointConversion to reduce it to 16 bits, or save it as OpenEXR or TIFF.
- A lossy file with an ICC profile is decoded to the colors of that profile, through its colorants and tone curves, and keeps the profile. A file whose profile converts with lookup tables throws an UnsupportedImageFeatureException.