JpegEncoder Class

Immutable settings for JPEG encoding.

public sealed class JpegEncoder : ImageEncoder

Remarks

The output is a JPEG (JFIF) whose quantization tables are those of ITU-T T.81 Annex K scaled by JpegEncoder.Quality: by default a baseline sequential one (one interleaved scan, the typical Huffman tables of Annex K, or tables computed from the image with JpegEncoder.OptimizeHuffmanTables), or a progressive one (JpegEncoder.Process), with restart markers every JpegEncoder.RestartInterval MCUs if set. Gray pixel formats produce a single grayscale component; color pixel formats produce full-range YCbCr subsampled according to JpegEncoder.ChromaSubsampling. The component layout follows the pixel format, never the pixel values.

JpegEncoder.BitDepth selects 12-bit samples (an extended sequential or progressive frame) and JpegEncoder.EntropyCoding arithmetic coding (SOF9 or SOF10 frames). JpegEncodingProcess.Lossless writes the samples exactly (SOF3, or SOF11 with arithmetic coding), with 2 to 16 bits and RGB components for color pixel formats.

JPEG stores exactly one frame: animated images and images with a poster frame are rejected with an UnsupportedImageFeatureException; use ImageFrame.Save to save one frame explicitly.

Losses beyond the inherent lossy compression require explicit settings: non-opaque pixels require JpegEncoder.BackgroundColor, and 16-bit pixel formats require JpegEncoder.AllowBitDepthReduction. Both are checked before any output is written.

Metadata (subject to ImageEncoder.MetadataHandling): EXIF (APP1, orientation and dimensions reconciled), standard XMP (APP1), ICC profile (APP2, split into chunks), resolution (JFIF density) and Comment text entries (COM, Latin-1).

The MCU rows of a frame of at least 65,536 pixels are converted, transformed and quantized by up to ImageConfiguration.MaxDegreeOfParallelism workers of the configuration of the image, a batch of rows at a time; the entropy coding stays sequential, so the output does not depend on the number of workers.

Inheritance
ImageEncoder JpegEncoder

Constructors

NameDescription
JpegEncoder()

JpegEncoder()

JpegEncoder.cs
public JpegEncoder()

No documentation is available.

Properties

NameDescription
AllowBitDepthReductionGets a value indicating whether pixel formats deeper than the precision of the output (16-bit pixel formats, unless JpegEncoder.BitDepth is 16 with JpegEncodingProcess.Lossless) may be reduced to it (nearest rounding) when JpegEncoder.BitDepth is not set. Defaults to false.
BackgroundColorGets the opaque background color non-opaque pixels are composited over, interpreted in the encoded color space of the image (sRGB when untagged), or null to reject non-opaque pixels. Fully opaque images never need it.
BitDepthGets the sample precision of the output, or null (the default) for 8 bits with the DCT processes and the depth of the pixel format (8 or 16 bits) with JpegEncodingProcess.Lossless.
ChromaSubsamplingGets the chroma subsampling. Defaults to JpegChromaSubsampling.Auto.
EntropyCodingGets the entropy coding of the output. Defaults to JpegEntropyCoding.Huffman.
FormatGets the format produced by this encoder.
GainMapGets the gain map written next to the image, or null (the default) for none.
LosslessPredictorGets the predictor of JpegEncodingProcess.Lossless output, 1 to 7 (T.81 table H.1). Defaults to 1.
OptimizeHuffmanTablesGets a value indicating whether a baseline JPEG uses Huffman tables computed from the image instead of the typical tables of Annex K. Defaults to false.
ProcessGets the coding process. Defaults to JpegEncodingProcess.Baseline.
QualityGets the quality, from 1 (smallest) to 100 (best). Defaults to 90.
RestartIntervalGets the number of minimum coded units (MCUs) between two restart markers, or 0 (the default) for no restart marker.

AllowBitDepthReduction

JpegEncoder.cs

Gets a value indicating whether pixel formats deeper than the precision of the output (16-bit pixel formats, unless JpegEncoder.BitDepth is 16 with JpegEncodingProcess.Lossless) may be reduced to it (nearest rounding) when JpegEncoder.BitDepth is not set. Defaults to false.

public bool AllowBitDepthReduction { get; init; }

Property value

bool

BackgroundColor

JpegEncoder.cs

Gets the opaque background color non-opaque pixels are composited over, interpreted in the encoded color space of the image (sRGB when untagged), or null to reject non-opaque pixels. Fully opaque images never need it.

public Rgba64? BackgroundColor { get; init; }

Property value

Rgba64?

Exceptions

ArgumentException
The color is not fully opaque.

Gets the sample precision of the output, or null (the default) for 8 bits with the DCT processes and the depth of the pixel format (8 or 16 bits) with JpegEncodingProcess.Lossless.

public int? BitDepth { get; init; }

Property value

int?

Exceptions

ArgumentOutOfRangeException
The value is not between 2 and 16.

Remarks

The DCT processes (JpegEncodingProcess.Baseline and JpegEncodingProcess.Progressive) take 8 or 12 bits; the lossless process takes 2 to 16 bits. Samples are scaled to the precision with nearest rounding (8-bit pixels are scaled up exactly). A value below the depth of a 16-bit pixel format is the consent to reduce its samples (as JpegEncoder.AllowBitDepthReduction is for the default).

12-bit output is an extended sequential (SOF1) or progressive frame with the same quantization tables as 8-bit output (as libjpeg writes it), so its coefficients are quantized 16 times more finely relative to the sample range. The Huffman tables of a 12-bit or lossless frame are always computed from the image (the typical tables of Annex K do not cover their categories), and the coefficients of the whole image are kept in memory until the scan is written. Some decoders (most web browsers among them) do not read 12-bit or lossless files.

ChromaSubsampling

JpegEncoder.cs

Gets the chroma subsampling. Defaults to JpegChromaSubsampling.Auto.

public JpegChromaSubsampling ChromaSubsampling { get; init; }

Property value

JpegChromaSubsampling

Exceptions

ArgumentOutOfRangeException
The value is not a defined JpegChromaSubsampling.

Remarks

Subsampled chroma is the mean of the full-resolution samples each chroma sample covers (box filter, centered siting). The setting has no effect on gray pixel formats, which are written as a single component.

EntropyCoding

JpegEncoder.cs

Gets the entropy coding of the output. Defaults to JpegEntropyCoding.Huffman.

public JpegEntropyCoding EntropyCoding { get; init; }

Property value

JpegEntropyCoding

Exceptions

ArgumentOutOfRangeException
The value is not a defined JpegEntropyCoding.

Remarks

Arithmetic coding stores the coefficients (or, with JpegEncodingProcess.Lossless, the sample differences) of Huffman coding with the default conditioning of T.81 (no DAC segment), so the output decodes to the same pixels and is usually smaller. As with optimized Huffman tables, the coefficients of the whole image are kept in memory until the scans are written (two bytes per coefficient).

Gets the format produced by this encoder.

public override ImageFormat Format { get; }

Property value

ImageFormat

Gets the gain map written next to the image, or null (the default) for none.

public GainMap? GainMap { get; init; }

Property value

GainMap?

Remarks

The file is an Ultra HDR file: the gain map image is a second JPEG image after the primary image, which a Multi-Picture Format index (APP2 MPF) locates. The parameters are written twice, as the metadata of ISO 21496-1 (an APP2 segment in each image, the primary image only giving the version) and as the hdrgm XMP properties of Adobe and Ultra HDR 1.0 (in the XMP packet of the gain map image, with a container directory in the one of the primary image, merged with the XMP packet of each image when it has one), which cannot express GainMapMetadata.UseBaseColorSpace set to false. The encoded images are kept in memory until the file is written, since the index of the primary image gives the length of both. The image must be a still image. The gain map image is encoded with the same settings but full chroma resolution (JpegChromaSubsampling.Ratio444: the gain amplifies its errors), and its metadata (the ICC profile of the alternate rendition) with ImageEncoder.MetadataHandling. A gain map is only written with 8-bit Huffman-coded output (JpegEncodingProcess.Baseline or JpegEncodingProcess.Progressive), which Ultra HDR readers decode: the image is rejected with an ArgumentException otherwise.

LosslessPredictor

JpegEncoder.cs

Gets the predictor of JpegEncodingProcess.Lossless output, 1 to 7 (T.81 table H.1). Defaults to 1.

public int LosslessPredictor { get; init; }

Property value

int

Exceptions

ArgumentOutOfRangeException
The value is not between 1 and 7.

Remarks

With Ra the sample on the left, Rb the one above and Rc the one above on the left, the predictors are Ra (1), Rb (2), Rc (3), Ra + Rb - Rc (4), Ra + ((Rb - Rc) >> 1) (5), Rb + ((Ra - Rc) >> 1) (6) and (Ra + Rb) >> 1 (7). The first line uses Ra and the first sample of the other lines Rb. The predictor that gives the smallest file depends on the image; every predictor gives the same decoded samples. The point transform is always 0: every bit of the samples is kept.

OptimizeHuffmanTables

JpegEncoder.cs

Gets a value indicating whether a baseline JPEG uses Huffman tables computed from the image instead of the typical tables of Annex K. Defaults to false.

public bool OptimizeHuffmanTables { get; init; }

Property value

bool

Remarks

The image is coded twice from its quantized coefficients: once to count the symbols of each table, from which length-limited codes are built (ITU-T T.81 section K.2: at most 16 bits, no code made of 1-bits only), then to write the scan with them. The quantized coefficients, and so the decoded pixels, are those of the default output; only the DHT segment and the size of the entropy-coded data change, usually a few percent smaller. As with the progressive process, the coefficients of the whole image are kept in memory until the scan is written (two bytes per coefficient), where the default baseline output only keeps a few rows. It has no effect on JpegEncodingProcess.Progressive, whose scans always use tables computed from their own symbols.

Gets the coding process. Defaults to JpegEncodingProcess.Baseline.

public JpegEncodingProcess Process { get; init; }

Property value

JpegEncodingProcess

Exceptions

ArgumentOutOfRangeException
The value is not a defined JpegEncodingProcess.

Remarks

Both processes store the same quantized coefficients, so they decode to the same pixels. JpegEncodingProcess.Progressive writes them in several scans (six for a grayscale image, ten for a color one), each with Huffman tables computed from its own statistics: the DC coefficients without their lowest bit, the first five AC coefficients of the luminance without their two lowest bits, the chrominance without its lowest bit, the rest of the luminance, then the missing bits. The coefficients of the whole image are kept in memory until the last scan (two bytes per coefficient), where the baseline process only keeps a few rows.

Gets the quality, from 1 (smallest) to 100 (best). Defaults to 90.

public int Quality { get; init; }

Property value

int

Exceptions

ArgumentOutOfRangeException
The value is not between 1 and 100.

Remarks

The Annex K tables are scaled linearly: with s = 5000 / Quality below 50 and s = 200 - 2 * Quality otherwise, each quantization value is clamp((base * s + 50) / 100, 1, 255). Quality 50 uses the Annex K tables unchanged and 100 quantizes every coefficient by 1 (still lossy: color conversion and rounding remain).

RestartInterval

JpegEncoder.cs

Gets the number of minimum coded units (MCUs) between two restart markers, or 0 (the default) for no restart marker.

public int RestartInterval { get; init; }

Property value

int

Exceptions

ArgumentOutOfRangeException
The value is not between 0 and 65,535.

Remarks

With a nonzero interval, a DRI segment precedes the first scan and each scan is split into intervals of that many MCUs, in raster order (ITU-T T.81 sections B.2.4.4 and F.1.2.3): every interval but the last ends with the 1-bits that complete its last byte and a marker from RST0 to RST7 (cyclically), and the next interval starts again with DC predictions of 0 (and, in a progressive scan, without a pending end-of-band run). A decoder can then resynchronize after corrupted data, or decode the intervals independently. The decoded pixels do not change: only a few bytes are added per marker, and the end-of-band runs of a progressive scan are shorter.

An MCU of the interleaved scans covers 8x8 pixels for a grayscale image or 4:4:4 chroma, 16x8 for 4:2:2 and 16x16 for 4:2:0; in the single-component scans of the progressive process, it is one 8x8 block of the component. An interval equal to the number of MCUs of a row of the baseline scan, ceil(width / MCU width), puts a marker before every MCU row but the first.