Image Class

An owned, disposable image made of one or more full-canvas displayed frames sharing one pixel format.

public abstract class Image : IDisposable

Remarks

Image is the untyped view of an image; every instance is an Image<TPixel> for one of the built-in pixel structs. The untyped and typed views expose the same frame objects, without copies.

Invariants:

  • The canvas has positive dimensions and there is always at least one displayed frame.
  • Every attached frame (including the optional Image.PosterFrame) has the canvas size and the image pixel format.
  • Frames are complete displayed images. Encoded delta rectangles, blend and disposal instructions are codec internals that are resolved on decode and recomputed on encode; they are not part of the model.
  • Attached frames are borrowed views owned by the image. Operations that extract frames (Image.CloneFrame, Image.ClonePosterFrame) return new independently disposable images.

Geometry-changing operations (crop, auto-crop, resize, rotate, auto-orient) apply to every frame and to the poster frame atomically: on failure before commit, the image is unchanged. Pixel-only operations (flip, grayscale, convolve, row callbacks) may leave the image partially modified on failure or cancellation, but always structurally valid.

An image is not thread-safe for concurrent mutation. Concurrent read-only access is allowed only while no operation mutates the image or holds a pixel lease.

Implements

Properties

NameDescription
AnimationGets or sets the animation-wide settings, or null for a still image.
ConfigurationGets the configuration captured when the image was created or loaded.
FramesGets the displayed frames, in playback order. Never empty.
HeightGets the canvas height, in pixels.
IsAnimatedGets a value indicating whether the image is an animation: it has more than one frame, a poster frame, or animation settings (Image.Animation is not null).
MetadataGets the mutable image-wide metadata.
PixelFormatGets the pixel format shared by every frame.
PosterFrameGets the separate poster frame, or null if none. A poster frame is a static image shown by decoders that do not support animation (APNG default image that is not part of the animation). It is not included in Image.Frames.
SizeGets the canvas size, in pixels. Always positive in both dimensions.
WidthGets the canvas width, in pixels.

Animation

Image.cs

Gets or sets the animation-wide settings, or null for a still image.

public AnimationMetadata? Animation { get; set; }

Property value

AnimationMetadata?

Exceptions

InvalidOperationException
The value is null while the image has several frames or a poster frame.
ObjectDisposedException
The image is disposed.

Remarks

Adding a second frame or a poster frame creates default settings (infinite loop) when none exist. Removing frames down to one does not remove the settings: a single-frame image with animation settings is still animated and is saved as a one-frame animation.

The setter stores a copy of the value. Setting null is only allowed when the image has a single frame and no poster frame.

Configuration

Image.cs

Gets the configuration captured when the image was created or loaded.

public ImageConfiguration Configuration { get; }

Property value

ImageConfiguration

Exceptions

ObjectDisposedException
The image is disposed.

Frames

Gets the displayed frames, in playback order. Never empty.

public abstract ImageFrameCollection Frames { get; }

Property value

ImageFrameCollection

Exceptions

ObjectDisposedException
The image is disposed.

Remarks

Structural edits (insert, remove, move) invalidate enumerators; surviving frame objects keep their identity when frames are moved.

Height

Image.cs

Gets the canvas height, in pixels.

public int Height { get; }

Property value

int

IsAnimated

Image.cs

Gets a value indicating whether the image is an animation: it has more than one frame, a poster frame, or animation settings (Image.Animation is not null).

public bool IsAnimated { get; }

Property value

bool

Exceptions

ObjectDisposedException
The image is disposed.

Metadata

Image.cs

Gets the mutable image-wide metadata.

public ImageMetadata Metadata { get; }

Property value

ImageMetadata

Exceptions

ObjectDisposedException
The image is disposed.

PixelFormat

Gets the pixel format shared by every frame.

public abstract PixelFormat PixelFormat { get; }

Property value

PixelFormat

PosterFrame

Gets the separate poster frame, or null if none. A poster frame is a static image shown by decoders that do not support animation (APNG default image that is not part of the animation). It is not included in Image.Frames.

public abstract ImageFrame? PosterFrame { get; }

Property value

ImageFrame?

Exceptions

ObjectDisposedException
The image is disposed.

Gets the canvas size, in pixels. Always positive in both dimensions.

public Size Size { get; }

Property value

Size

Exceptions

ObjectDisposedException
The image is disposed.

Gets the canvas width, in pixels.

public int Width { get; }

Property value

int

Methods

NameDescription
AppendFrame()Appends a new frame whose pixels are all zero (transparent black, or black for formats without alpha) and whose duration is zero.
AppendFrame(ImageFrame)Appends a copy of a frame. Pixels and frame metadata are copied; the source is not attached.
Clone()Creates an independent deep copy of the image: frames, poster frame, metadata and animation settings.
CloneAs<TPixel>(PixelConversionOptions?)Creates an independent copy of the image converted to another pixel format.
CloneFrame(int)Extracts a copy of one displayed frame as a new single-frame still image. The copy keeps the frame duration and the image-wide metadata, but not the animation settings or the poster frame.
ClonePosterFrame()Extracts a copy of the poster frame as a new single-frame still image with the image-wide metadata.
CreateWriter<TPixel>(Stream, ImageWriterOptions)Creates a writer that encodes frames one by one to a stream, starting at its current position. Seeking is never required.
CreateWriter<TPixel>(string, ImageWriterOptions)Creates a writer that encodes frames one by one to a file. Output goes to a temporary file in the same directory that is published to path only by a successful ImageWriter<TPixel>.Complete; disposing an uncompleted or failed writer deletes the temporary file and leaves any existing destination unchanged.
DetectFormat(ReadOnlySpan<byte>)Detects the format of encoded image data from its first bytes. File names and extensions are never used.
Dispose()Releases the pixel storage of every frame and of the poster frame. Borrowed frame references become invalid. Disposing more than once has no effect.
Draw(DrawingAction, CancellationToken)Draws on every frame of the image and on the poster frame: each shape is painted identically on all of them.
Draw<TState>(TState, DrawingAction<TState>, CancellationToken)Draws on every frame of the image and on the poster frame, passing caller state to avoid closure allocations.
Identify(Stream, ImageIdentifyOptions?)Reads information about an image from a stream, starting at its current position, without decoding pixels. The bytes read are consumed (the stream is not rewound) and the stream is left open. Non-seekable streams are supported.
Identify(ReadOnlySpan<byte>, ImageIdentifyOptions?)Reads information about in-memory encoded image data without decoding pixels.
Identify(string, ImageIdentifyOptions?)Reads information about an image file without decoding its pixels.
IdentifyAsync(Stream, ImageIdentifyOptions?, CancellationToken)Asynchronously reads information about an image from a stream, starting at its current position. The stream is left open.
IdentifyAsync(string, ImageIdentifyOptions?, CancellationToken)Asynchronously reads information about an image file without decoding its pixels.
ImportPixelBytes<TPixel>(ReadOnlySpan<byte>, int, int, int, ImageConfiguration?)Creates a single-frame image by copying raw pixel bytes laid out like TPixel (16-bit components in native endianness). The source memory is never wrapped or retained.
ImportPixelData<TPixel>(ReadOnlySpan<TPixel>, int, int, int, ImageConfiguration?)Creates a single-frame image by copying raw pixels. The source memory is never wrapped or retained.
InsertFrame(int, ImageFrame)Inserts a copy of a frame at the specified index. Pixels and frame metadata are copied; the source is not attached.
Load(Stream, ImageDecodeOptions?)Decodes an image from a stream, starting at its current position, into its default pixel format. Non-seekable streams are supported. The stream is left open and is not retained after the method returns.
Load(ReadOnlySpan<byte>, ImageDecodeOptions?)Decodes in-memory encoded image data into its default pixel format. The data is not retained.
Load(ReadOnlySpan<byte>, ImageDecodeOptions?, CancellationToken)Decodes in-memory encoded image data into its default pixel format, and can be canceled. The data is not retained.
Load(string, ImageDecodeOptions?)Decodes an image file into its default pixel format (see ImageInfo.PixelFormat).
Load<TPixel>(Stream, ImageDecodeOptions?)Decodes an image from a stream, starting at its current position, into the requested pixel type. The stream is left open.
Load<TPixel>(ReadOnlySpan<byte>, ImageDecodeOptions?)Decodes in-memory encoded image data into the requested pixel type.
Load<TPixel>(ReadOnlySpan<byte>, ImageDecodeOptions?, CancellationToken)Decodes in-memory encoded image data into the requested pixel type, and can be canceled.
Load<TPixel>(string, ImageDecodeOptions?)Decodes an image file into the requested pixel type.
LoadAsync(Stream, ImageDecodeOptions?, CancellationToken)Asynchronously decodes an image from a stream, starting at its current position, into its default pixel format. The stream is left open.
LoadAsync(string, ImageDecodeOptions?, CancellationToken)Asynchronously decodes an image file into its default pixel format, using asynchronous file I/O.
LoadAsync<TPixel>(Stream, ImageDecodeOptions?, CancellationToken)Asynchronously decodes an image from a stream, starting at its current position, into the requested pixel type. The stream is left open.
LoadAsync<TPixel>(string, ImageDecodeOptions?, CancellationToken)Asynchronously decodes an image file into the requested pixel type.
MoveFrame(int, int)Moves a frame to a new position. Frame objects keep their identity.
OpenReader<TPixel>(Stream, ImageReaderOptions?)Opens a stream for sequential frame-by-frame decoding, starting at its current position. Non-seekable streams are supported.
OpenReader<TPixel>(string, ImageReaderOptions?)Opens a file for sequential frame-by-frame decoding. Only one displayed frame of compositor state is kept in memory, regardless of the number of frames, as long as the caller disposes the frames it reads.
OpenReaderAsync<TPixel>(Stream, ImageReaderOptions?, CancellationToken)Asynchronously opens a stream for sequential frame-by-frame decoding, starting at its current position.
OpenReaderAsync<TPixel>(string, ImageReaderOptions?, CancellationToken)Asynchronously opens a file for sequential frame-by-frame decoding.
RemoveFrame(int)Removes a frame. References to the removed frame become invalid and throw ObjectDisposedException on use.
RemovePosterFrame()Removes the poster frame, if any. References to the removed poster frame become invalid.
Save(Stream, ImageEncoder)Encodes the image to a stream, starting at its current position. The stream is left open.
Save(string, ImageEncoder?)Encodes the image to a file. The file is written to a temporary file in the same directory and published only after encoding succeeds; on failure an existing file at path is left unchanged.
SaveAsync(Stream, ImageEncoder, CancellationToken)Asynchronously encodes the image to a stream, starting at its current position. The stream is left open.
SaveAsync(string, ImageEncoder?, CancellationToken)Asynchronously encodes the image to a file, with the same atomic-publication guarantees as Image.Save.
SetPosterFrame(ImageFrame)Sets the poster frame to a copy of a frame, replacing (and invalidating) any existing poster frame. Creates default animation settings when none exist.

AppendFrame overloads

AppendFrame()

Appends a new frame whose pixels are all zero (transparent black, or black for formats without alpha) and whose duration is zero.

public abstract ImageFrame AppendFrame()
Returns

ImageFrame The attached frame.

Exceptions
ImageResourceLimitException
The frame would exceed the configured frame count (displayed frames plus poster) or allocation limit; the image is unchanged.
InvalidOperationException
A pixel lease is active.
ObjectDisposedException
The image is disposed.

AppendFrame(ImageFrame)

Appends a copy of a frame. Pixels and frame metadata are copied; the source is not attached.

public abstract ImageFrame AppendFrame(ImageFrame source)
Parameters
source ImageFrame
The frame to copy. It must have the canvas size and the pixel format of this image; it may belong to this image.
Returns

ImageFrame The attached copy.

Exceptions
ArgumentException
source has a different size or pixel format. Frames are never resized or converted implicitly.
ImageResourceLimitException
The frame would exceed the configured frame count (displayed frames plus poster) or allocation limit; the image is unchanged.
InvalidOperationException
A pixel lease of the image is active, or the source frame is leased.
ObjectDisposedException
The image or the source is disposed.

Clone()

Creates an independent deep copy of the image: frames, poster frame, metadata and animation settings.

public abstract Image Clone()

Returns

Image A new image owned by the caller, with its own allocation scope.

Exceptions

ObjectDisposedException
The image is disposed.
ImageResourceLimitException
The copy would exceed the configured allocation limit.

CloneAs<TPixel>(PixelConversionOptions?)

Image.cs

Creates an independent copy of the image converted to another pixel format.

public Image<TPixel> CloneAs<TPixel>(PixelConversionOptions? options = null) where TPixel : unmanaged

Type parameters

TPixel
The target pixel type.

Parameters

options PixelConversionOptions?
The conversion options, or null for PixelConversionOptions.Default.

Returns

Image<TPixel> A new image owned by the caller.

Exceptions

NotSupportedException
TPixel is not a built-in pixel struct.
UnsupportedImageFeatureException
The conversion would drop non-opaque alpha without PixelConversionOptions.BackgroundColor, would retain an incompatible ICC profile, or would have to store floating-point samples that are not numbers, or that are out of the range of TPixel without PixelConversionOptions.OutOfRangeSamples or PixelConversionOptions.ToneMapping. Nothing is allocated.
ObjectDisposedException
The image is disposed.

CloneFrame(int)

Extracts a copy of one displayed frame as a new single-frame still image. The copy keeps the frame duration and the image-wide metadata, but not the animation settings or the poster frame.

public abstract Image CloneFrame(int index)

Parameters

index int
The index of the frame in Image.Frames.

Returns

Image A new image owned by the caller.

Exceptions

ArgumentOutOfRangeException
index is out of range.
ObjectDisposedException
The image is disposed.

ClonePosterFrame()

Extracts a copy of the poster frame as a new single-frame still image with the image-wide metadata.

public abstract Image ClonePosterFrame()

Returns

Image A new image owned by the caller.

Exceptions

InvalidOperationException
The image has no poster frame.
ObjectDisposedException
The image is disposed.

CreateWriter overloads

CreateWriter<TPixel>(Stream, ImageWriterOptions)

Image.Streaming.cs

Creates a writer that encodes frames one by one to a stream, starting at its current position. Seeking is never required.

public static ImageWriter<TPixel> CreateWriter<TPixel>(Stream stream, ImageWriterOptions options) where TPixel : unmanaged
Type parameters
TPixel
The pixel type of the frames written.
Parameters
stream Stream
The writable destination stream. It is left open unless ImageWriterOptions.LeaveOpen is false.
options ImageWriterOptions
The writer options. ImageWriterOptions.Encoder is required.
Returns

ImageWriter<TPixel> A writer ready to accept the poster frame (if any) and the displayed frames.

Exceptions
NotSupportedException
TPixel is not a built-in pixel struct.
ArgumentException
stream is not writable, no encoder is specified, or the options are invalid for the encoder.

CreateWriter<TPixel>(string, ImageWriterOptions)

Image.Streaming.cs

Creates a writer that encodes frames one by one to a file. Output goes to a temporary file in the same directory that is published to path only by a successful ImageWriter<TPixel>.Complete; disposing an uncompleted or failed writer deletes the temporary file and leaves any existing destination unchanged.

public static ImageWriter<TPixel> CreateWriter<TPixel>(string path, ImageWriterOptions options) where TPixel : unmanaged
Type parameters
TPixel
The pixel type of the frames written.
Parameters
path string
The destination path.
options ImageWriterOptions
The writer options. ImageWriterOptions.Encoder may be null to select the encoder from the file extension.
Returns

ImageWriter<TPixel> A writer ready to accept the poster frame (if any) and the displayed frames.

Exceptions
NotSupportedException
TPixel is not a built-in pixel struct. Thrown before any I/O.
ArgumentException
path is empty or has an unrecognized extension while no encoder is specified, or the options are invalid for the encoder (for example PNG without ImageWriterOptions.ExpectedFrameCount).
IOException
An I/O error occurred.

DetectFormat(ReadOnlySpan<byte>)

Image.Load.cs

Detects the format of encoded image data from its first bytes. File names and extensions are never used.

public static ImageFormat DetectFormat(ReadOnlySpan<byte> prefix)

Parameters

prefix ReadOnlySpan<byte>
The first bytes of the data. Provide at least Image.FormatDetectionPrefixLength bytes; a prefix shorter than 8 bytes is reported as ImageFormat.Unknown, as no valid supported image is that short, WebP is only recognized from 12 bytes and TGA only from 18.

Returns

ImageFormat The detected format, or ImageFormat.Unknown if the signature is not recognized. APNG files are reported as ImageFormat.Png.

Dispose()

Image.cs

Releases the pixel storage of every frame and of the poster frame. Borrowed frame references become invalid. Disposing more than once has no effect.

public void Dispose()

Exceptions

InvalidOperationException
A pixel lease is active (for example, Dispose is called from a row callback).

Draw overloads

Draw(DrawingAction, CancellationToken)

Image.Drawing.cs

Draws on every frame of the image and on the poster frame: each shape is painted identically on all of them.

public void Draw(DrawingAction action, CancellationToken cancellationToken = default)
Parameters
action DrawingAction
The callback that draws. It must not be asynchronous and must not retain the canvas.
cancellationToken CancellationToken
The token to monitor for cancellation requests. It is checked by every drawing call.
Exceptions
ArgumentNullException
action is null.
InvalidOperationException
A pixel lease is active.
ImageResourceLimitException
The working storage would exceed the allocation limit.
OperationCanceledException
The operation was canceled. The shapes already drawn stay, and some rows of the one being drawn may be painted, the same rows on every frame.
ObjectDisposedException
The image is disposed.
Remarks

The callback runs once. See DrawingCanvas for the coordinates and the rendering rules, and ImageFrame.Draw to draw on a single frame.

Draw<TState>(TState, DrawingAction<TState>, CancellationToken)

Image.Drawing.cs

Draws on every frame of the image and on the poster frame, passing caller state to avoid closure allocations.

public void Draw<TState>(TState state, DrawingAction<TState> action, CancellationToken cancellationToken = default) where TState : allows ref struct
Type parameters
TState
The type of the state.
Parameters
state TState
The state passed to action.
action DrawingAction<TState>
The callback that draws. Use a static lambda to avoid allocations. It must not retain the canvas.
cancellationToken CancellationToken
The token to monitor for cancellation requests. It is checked by every drawing call.
Exceptions
ArgumentNullException
action is null.
InvalidOperationException
A pixel lease is active.
ImageResourceLimitException
The working storage would exceed the allocation limit.
OperationCanceledException
The operation was canceled. The shapes already drawn stay, and some rows of the one being drawn may be painted, the same rows on every frame.
ObjectDisposedException
The image is disposed.

Identify overloads

Identify(Stream, ImageIdentifyOptions?)

Image.Load.cs

Reads information about an image from a stream, starting at its current position, without decoding pixels. The bytes read are consumed (the stream is not rewound) and the stream is left open. Non-seekable streams are supported.

public static ImageInfo Identify(Stream stream, ImageIdentifyOptions? options = null)
Parameters
stream Stream
The readable source stream.
options ImageIdentifyOptions?
The options, or null for ImageIdentifyOptions.Default.
Returns

ImageInfo The image information.

Exceptions
ArgumentException
stream is not readable.
UnknownImageFormatException
The format is not recognized.
InvalidImageContentException
The examined data is malformed or truncated.
UnsupportedImageFeatureException
The data uses a recognized but unsupported feature.
ImageResourceLimitException
A configured limit is exceeded.
IOException
An I/O error occurred.
Remarks

TIFF, BigTIFF, ICO, CUR and ANI are random-access containers: on a seekable stream only the bytes their structure points at are read, the stream is seeked freely and its position afterward is unspecified. A non-seekable stream is buffered instead, bounded by ImageResourceLimits.MaxEncodedBytes. Use ImageCollection to read a large document or to reach a page or representation other than the first one (ImageInfo.CollectionEntryCount reports how many there are).

Identify(ReadOnlySpan<byte>, ImageIdentifyOptions?)

Image.Load.cs

Reads information about in-memory encoded image data without decoding pixels.

public static ImageInfo Identify(ReadOnlySpan<byte> data, ImageIdentifyOptions? options = null)
Parameters
data ReadOnlySpan<byte>
The encoded data.
options ImageIdentifyOptions?
The options, or null for ImageIdentifyOptions.Default.
Returns

ImageInfo The image information.

Exceptions
UnknownImageFormatException
The format is not recognized.
InvalidImageContentException
The examined data is malformed or truncated.
UnsupportedImageFeatureException
The data uses a recognized but unsupported feature.
ImageResourceLimitException
A configured limit is exceeded.

Identify(string, ImageIdentifyOptions?)

Image.Load.cs

Reads information about an image file without decoding its pixels.

public static ImageInfo Identify(string path, ImageIdentifyOptions? options = null)
Parameters
path string
The path of the file.
options ImageIdentifyOptions?
The options, or null for ImageIdentifyOptions.Default.
Returns

ImageInfo The image information. Values that cannot be determined in the selected mode are null.

Exceptions
ArgumentException
path is empty.
UnknownImageFormatException
The format is not recognized.
InvalidImageContentException
The examined data is malformed or truncated.
UnsupportedImageFeatureException
The file uses a recognized but unsupported feature.
ImageResourceLimitException
A configured limit is exceeded.
IOException
An I/O error occurred.

IdentifyAsync overloads

IdentifyAsync(Stream, ImageIdentifyOptions?, CancellationToken)

Image.Load.cs

Asynchronously reads information about an image from a stream, starting at its current position. The stream is left open.

public static Task<ImageInfo> IdentifyAsync(Stream stream, ImageIdentifyOptions? options = null, CancellationToken cancellationToken = default)
Parameters
stream Stream
The readable source stream.
options ImageIdentifyOptions?
The options, or null for ImageIdentifyOptions.Default.
cancellationToken CancellationToken
The token to monitor for cancellation requests.
Returns

Task<ImageInfo> The image information.

Exceptions
ArgumentException
stream is not readable.
OperationCanceledException
The operation was canceled.
Remarks

Asynchronous loads of the random-access containers (TIFF, BigTIFF, ICO, CUR, ANI) read the whole input into memory first, bounded by ImageResourceLimits.MaxEncodedBytes: their structure is a graph of file offsets, so awaiting every tag would gain nothing. Use the synchronous overloads or ImageCollection for a large document.

IdentifyAsync(string, ImageIdentifyOptions?, CancellationToken)

Image.Load.cs

Asynchronously reads information about an image file without decoding its pixels.

public static Task<ImageInfo> IdentifyAsync(string path, ImageIdentifyOptions? options = null, CancellationToken cancellationToken = default)
Parameters
path string
The path of the file.
options ImageIdentifyOptions?
The options, or null for ImageIdentifyOptions.Default.
cancellationToken CancellationToken
The token to monitor for cancellation requests.
Returns

Task<ImageInfo> The image information.

Exceptions
ArgumentException
path is empty.
OperationCanceledException
The operation was canceled.
Remarks

Asynchronous loads of the random-access containers (TIFF, BigTIFF, ICO, CUR, ANI) read the whole input into memory first, bounded by ImageResourceLimits.MaxEncodedBytes: their structure is a graph of file offsets, so awaiting every tag would gain nothing. Use the synchronous overloads or ImageCollection for a large document.

ImportPixelBytes<TPixel>(ReadOnlySpan<byte>, int, int, int, ImageConfiguration?)

Image.Load.cs

Creates a single-frame image by copying raw pixel bytes laid out like TPixel (16-bit components in native endianness). The source memory is never wrapped or retained.

public static Image<TPixel> ImportPixelBytes<TPixel>(ReadOnlySpan<byte> source, int width, int height, int strideInBytes = 0, ImageConfiguration? configuration = null) where TPixel : unmanaged

Type parameters

TPixel
The pixel type of the source layout and of the result.

Parameters

source ReadOnlySpan<byte>
The source bytes, row by row, top to bottom.
width int
The width of the image. Must be positive.
height int
The height of the image. Must be positive.
strideInBytes int
The distance between the starts of two consecutive source rows, in bytes, or 0 for tightly packed rows. Must be 0 or at least width * bytesPerPixel; it does not need to be a multiple of the pixel size.
configuration ImageConfiguration?
The configuration of the new image, or null for ImageConfiguration.Default.

Returns

Image<TPixel> A new image owned by the caller.

Exceptions

NotSupportedException
TPixel is not a built-in pixel struct.
ArgumentOutOfRangeException
A dimension or the stride is invalid.
ArgumentException
source is too short for the dimensions and stride.
ImageResourceLimitException
The image would exceed a configured limit.

ImportPixelData<TPixel>(ReadOnlySpan<TPixel>, int, int, int, ImageConfiguration?)

Image.Load.cs

Creates a single-frame image by copying raw pixels. The source memory is never wrapped or retained.

public static Image<TPixel> ImportPixelData<TPixel>(ReadOnlySpan<TPixel> source, int width, int height, int strideInPixels = 0, ImageConfiguration? configuration = null) where TPixel : unmanaged

Type parameters

TPixel
The pixel type of the source and of the result.

Parameters

source ReadOnlySpan<TPixel>
The source pixels, row by row, top to bottom.
width int
The width of the image. Must be positive.
height int
The height of the image. Must be positive.
strideInPixels int
The distance between the starts of two consecutive source rows, in pixels, or 0 for tightly packed rows (equivalent to width). Must be 0 or at least width.
configuration ImageConfiguration?
The configuration of the new image, or null for ImageConfiguration.Default.

Returns

Image<TPixel> A new image owned by the caller.

Exceptions

NotSupportedException
TPixel is not a built-in pixel struct.
ArgumentOutOfRangeException
A dimension or the stride is invalid.
ArgumentException
source is too short for the dimensions and stride (the last row only needs width pixels).
ImageResourceLimitException
The image would exceed a configured limit.

InsertFrame(int, ImageFrame)

Inserts a copy of a frame at the specified index. Pixels and frame metadata are copied; the source is not attached.

public abstract ImageFrame InsertFrame(int index, ImageFrame source)

Parameters

index int
The index at which the copy is inserted, from 0 to Frames.Count.
source ImageFrame
The frame to copy. It must have the canvas size and the pixel format of this image; it may belong to this image.

Returns

ImageFrame The attached copy.

Exceptions

ArgumentOutOfRangeException
index is out of range.
ArgumentException
source has a different size or pixel format.
ImageResourceLimitException
The frame would exceed the configured frame count (displayed frames plus poster) or allocation limit; the image is unchanged.
InvalidOperationException
A pixel lease of the image is active, or the source frame is leased.
ObjectDisposedException
The image or the source is disposed.

Load overloads

Load(Stream, ImageDecodeOptions?)

Image.Load.cs

Decodes an image from a stream, starting at its current position, into its default pixel format. Non-seekable streams are supported. The stream is left open and is not retained after the method returns.

public static Image Load(Stream stream, ImageDecodeOptions? options = null)
Parameters
stream Stream
The readable source stream.
options ImageDecodeOptions?
The options, or null for ImageDecodeOptions.Default.
Returns

Image A new image owned by the caller.

Exceptions
ArgumentException
stream is not readable.
UnknownImageFormatException
The format is not recognized.
InvalidImageContentException
The data is malformed or truncated.
UnsupportedImageFeatureException
The data uses a recognized but unsupported feature.
ImageResourceLimitException
A configured limit is exceeded.
IOException
An I/O error occurred.
Remarks

TIFF, BigTIFF, ICO, CUR and ANI are random-access containers: on a seekable stream only the bytes their structure points at are read, the stream is seeked freely and its position afterward is unspecified. A non-seekable stream is buffered instead, bounded by ImageResourceLimits.MaxEncodedBytes. Use ImageCollection to read a large document or to reach a page or representation other than the first one (ImageInfo.CollectionEntryCount reports how many there are).

Load(ReadOnlySpan<byte>, ImageDecodeOptions?)

Image.Load.cs

Decodes in-memory encoded image data into its default pixel format. The data is not retained.

public static Image Load(ReadOnlySpan<byte> data, ImageDecodeOptions? options)
Parameters
data ReadOnlySpan<byte>
The encoded data.
options ImageDecodeOptions?
The options, or null for ImageDecodeOptions.Default.
Returns

Image A new image owned by the caller.

Exceptions
UnknownImageFormatException
The format is not recognized.
InvalidImageContentException
The data is malformed or truncated.
UnsupportedImageFeatureException
The data uses a recognized but unsupported feature.
ImageResourceLimitException
A configured limit is exceeded.

Load(ReadOnlySpan<byte>, ImageDecodeOptions?, CancellationToken)

Image.Load.cs

Decodes in-memory encoded image data into its default pixel format, and can be canceled. The data is not retained.

public static Image Load(ReadOnlySpan<byte> data, ImageDecodeOptions? options = null, CancellationToken cancellationToken = default)
Parameters
data ReadOnlySpan<byte>
The encoded data.
options ImageDecodeOptions?
The options, or null for ImageDecodeOptions.Default.
cancellationToken CancellationToken
The token to monitor for cancellation requests.
Returns

Image A new image owned by the caller.

Exceptions
UnknownImageFormatException
The format is not recognized.
InvalidImageContentException
The data is malformed or truncated.
UnsupportedImageFeatureException
The data uses a recognized but unsupported feature.
ImageResourceLimitException
A configured limit is exceeded.
OperationCanceledException
The operation was canceled.
Remarks

The decode runs synchronously on the calling thread. The token is checked before any work and then between bounded units of work of the decoder (rows, strips, tiles or blocks, and frames), never in the middle of one: a cancellation is observed within one such unit. A canceled decode returns no image and releases every buffer it allocated.

Load(string, ImageDecodeOptions?)

Image.Load.cs

Decodes an image file into its default pixel format (see ImageInfo.PixelFormat).

public static Image Load(string path, ImageDecodeOptions? options = null)
Parameters
path string
The path of the file. The file is closed before the method returns.
options ImageDecodeOptions?
The options, or null for ImageDecodeOptions.Default.
Returns

Image A new image owned by the caller. Every displayed frame is decoded (up to ImageDecodeOptions.FrameLimit).

Exceptions
ArgumentException
path is empty.
UnknownImageFormatException
The format is not recognized.
InvalidImageContentException
The data is malformed or truncated.
UnsupportedImageFeatureException
The file uses a recognized but unsupported feature.
ImageResourceLimitException
A configured limit is exceeded.
IOException
An I/O error occurred.

Load<TPixel>(Stream, ImageDecodeOptions?)

Image.Load.cs

Decodes an image from a stream, starting at its current position, into the requested pixel type. The stream is left open.

public static Image<TPixel> Load<TPixel>(Stream stream, ImageDecodeOptions? options = null) where TPixel : unmanaged
Type parameters
TPixel
The pixel type of the result.
Parameters
stream Stream
The readable source stream.
options ImageDecodeOptions?
The options, or null for ImageDecodeOptions.Default.
Returns

Image<TPixel> A new image owned by the caller.

Exceptions
NotSupportedException
TPixel is not a built-in pixel struct. Thrown before any I/O.
ArgumentException
stream is not readable.
UnknownImageFormatException
The format is not recognized.
InvalidImageContentException
The data is malformed or truncated.
UnsupportedImageFeatureException
The data uses an unsupported feature, or the conversion would drop information without an explicit policy.
ImageResourceLimitException
A configured limit is exceeded.
IOException
An I/O error occurred.
Remarks

TIFF, BigTIFF, ICO, CUR and ANI are random-access containers: on a seekable stream only the bytes their structure points at are read, the stream is seeked freely and its position afterward is unspecified. A non-seekable stream is buffered instead, bounded by ImageResourceLimits.MaxEncodedBytes. Use ImageCollection to read a large document or to reach a page or representation other than the first one (ImageInfo.CollectionEntryCount reports how many there are).

Load<TPixel>(ReadOnlySpan<byte>, ImageDecodeOptions?)

Image.Load.cs

Decodes in-memory encoded image data into the requested pixel type.

public static Image<TPixel> Load<TPixel>(ReadOnlySpan<byte> data, ImageDecodeOptions? options) where TPixel : unmanaged
Type parameters
TPixel
The pixel type of the result.
Parameters
data ReadOnlySpan<byte>
The encoded data.
options ImageDecodeOptions?
The options, or null for ImageDecodeOptions.Default.
Returns

Image<TPixel> A new image owned by the caller.

Exceptions
NotSupportedException
TPixel is not a built-in pixel struct.
UnknownImageFormatException
The format is not recognized.
InvalidImageContentException
The data is malformed or truncated.
UnsupportedImageFeatureException
The data uses an unsupported feature, or the conversion would drop information without an explicit policy.
ImageResourceLimitException
A configured limit is exceeded.

Load<TPixel>(ReadOnlySpan<byte>, ImageDecodeOptions?, CancellationToken)

Image.Load.cs

Decodes in-memory encoded image data into the requested pixel type, and can be canceled.

public static Image<TPixel> Load<TPixel>(ReadOnlySpan<byte> data, ImageDecodeOptions? options = null, CancellationToken cancellationToken = default) where TPixel : unmanaged
Type parameters
TPixel
The pixel type of the result.
Parameters
data ReadOnlySpan<byte>
The encoded data.
options ImageDecodeOptions?
The options, or null for ImageDecodeOptions.Default.
cancellationToken CancellationToken
The token to monitor for cancellation requests.
Returns

Image<TPixel> A new image owned by the caller.

Exceptions
NotSupportedException
TPixel is not a built-in pixel struct. Thrown before the token is checked.
UnknownImageFormatException
The format is not recognized.
InvalidImageContentException
The data is malformed or truncated.
UnsupportedImageFeatureException
The data uses an unsupported feature, or the conversion would drop information without an explicit policy.
ImageResourceLimitException
A configured limit is exceeded.
OperationCanceledException
The operation was canceled.
Remarks

The decode runs synchronously on the calling thread. The token is checked before any work and then between bounded units of work of the decoder (rows, strips, tiles or blocks, and frames), never in the middle of one: a cancellation is observed within one such unit. A canceled decode returns no image and releases every buffer it allocated.

Load<TPixel>(string, ImageDecodeOptions?)

Image.Load.cs

Decodes an image file into the requested pixel type.

public static Image<TPixel> Load<TPixel>(string path, ImageDecodeOptions? options = null) where TPixel : unmanaged
Type parameters
TPixel
The pixel type of the result.
Parameters
path string
The path of the file. The file is closed before the method returns.
options ImageDecodeOptions?
The options, or null for ImageDecodeOptions.Default. ImageDecodeOptions.Conversion controls alpha removal and color profiles.
Returns

Image<TPixel> A new image owned by the caller.

Exceptions
NotSupportedException
TPixel is not a built-in pixel struct. Thrown before any I/O.
ArgumentException
path is empty.
UnknownImageFormatException
The format is not recognized.
InvalidImageContentException
The data is malformed or truncated.
UnsupportedImageFeatureException
The file uses an unsupported feature, or the conversion would drop information without an explicit policy.
ImageResourceLimitException
A configured limit is exceeded.
IOException
An I/O error occurred.

LoadAsync overloads

LoadAsync(Stream, ImageDecodeOptions?, CancellationToken)

Image.Load.cs

Asynchronously decodes an image from a stream, starting at its current position, into its default pixel format. The stream is left open.

public static Task<Image> LoadAsync(Stream stream, ImageDecodeOptions? options = null, CancellationToken cancellationToken = default)
Parameters
stream Stream
The readable source stream.
options ImageDecodeOptions?
The options, or null for ImageDecodeOptions.Default.
cancellationToken CancellationToken
The token to monitor for cancellation requests.
Returns

Task<Image> A new image owned by the caller.

Exceptions
ArgumentException
stream is not readable.
OperationCanceledException
The operation was canceled.
Remarks

Asynchronous loads of the random-access containers (TIFF, BigTIFF, ICO, CUR, ANI) read the whole input into memory first, bounded by ImageResourceLimits.MaxEncodedBytes: their structure is a graph of file offsets, so awaiting every tag would gain nothing. Use the synchronous overloads or ImageCollection for a large document.

LoadAsync(string, ImageDecodeOptions?, CancellationToken)

Image.Load.cs

Asynchronously decodes an image file into its default pixel format, using asynchronous file I/O.

public static Task<Image> LoadAsync(string path, ImageDecodeOptions? options = null, CancellationToken cancellationToken = default)
Parameters
path string
The path of the file.
options ImageDecodeOptions?
The options, or null for ImageDecodeOptions.Default.
cancellationToken CancellationToken
The token to monitor for cancellation requests.
Returns

Task<Image> A new image owned by the caller.

Exceptions
ArgumentException
path is empty.
OperationCanceledException
The operation was canceled. No image is returned and no buffer is leaked.

LoadAsync<TPixel>(Stream, ImageDecodeOptions?, CancellationToken)

Image.Load.cs

Asynchronously decodes an image from a stream, starting at its current position, into the requested pixel type. The stream is left open.

public static Task<Image<TPixel>> LoadAsync<TPixel>(Stream stream, ImageDecodeOptions? options = null, CancellationToken cancellationToken = default) where TPixel : unmanaged
Type parameters
TPixel
The pixel type of the result.
Parameters
stream Stream
The readable source stream.
options ImageDecodeOptions?
The options, or null for ImageDecodeOptions.Default.
cancellationToken CancellationToken
The token to monitor for cancellation requests.
Returns

Task<Image<TPixel>> A new image owned by the caller.

Exceptions
NotSupportedException
TPixel is not a built-in pixel struct. Thrown synchronously, before any I/O.
ArgumentException
stream is not readable.
OperationCanceledException
The operation was canceled.

LoadAsync<TPixel>(string, ImageDecodeOptions?, CancellationToken)

Image.Load.cs

Asynchronously decodes an image file into the requested pixel type.

public static Task<Image<TPixel>> LoadAsync<TPixel>(string path, ImageDecodeOptions? options = null, CancellationToken cancellationToken = default) where TPixel : unmanaged
Type parameters
TPixel
The pixel type of the result.
Parameters
path string
The path of the file.
options ImageDecodeOptions?
The options, or null for ImageDecodeOptions.Default.
cancellationToken CancellationToken
The token to monitor for cancellation requests.
Returns

Task<Image<TPixel>> A new image owned by the caller.

Exceptions
NotSupportedException
TPixel is not a built-in pixel struct. Thrown synchronously, before any I/O.
ArgumentException
path is empty.
OperationCanceledException
The operation was canceled.

MoveFrame(int, int)

Image.cs

Moves a frame to a new position. Frame objects keep their identity.

public void MoveFrame(int sourceIndex, int destinationIndex)

Parameters

sourceIndex int
The current index of the frame.
destinationIndex int
The final index of the frame after the move.

Exceptions

ArgumentOutOfRangeException
An index is out of range.
InvalidOperationException
A pixel lease is active.
ObjectDisposedException
The image is disposed.

OpenReader overloads

OpenReader<TPixel>(Stream, ImageReaderOptions?)

Image.Streaming.cs

Opens a stream for sequential frame-by-frame decoding, starting at its current position. Non-seekable streams are supported.

public static ImageReader<TPixel> OpenReader<TPixel>(Stream stream, ImageReaderOptions? options = null) where TPixel : unmanaged
Type parameters
TPixel
The pixel type of the frames returned by the reader.
Parameters
stream Stream
The readable source stream. It is left open unless ImageReaderOptions.LeaveOpen is false.
options ImageReaderOptions?
The options, or null for ImageReaderOptions.Default.
Returns

ImageReader<TPixel> A reader positioned before the first frame.

Exceptions
NotSupportedException
TPixel is not a built-in pixel struct. Thrown before any I/O.
ArgumentException
stream is not readable.
UnknownImageFormatException
The format is not recognized.
InvalidImageContentException
The header is malformed or truncated.
UnsupportedImageFeatureException
The data uses a recognized but unsupported feature.
ImageResourceLimitException
A configured limit is exceeded.
IOException
An I/O error occurred.

OpenReader<TPixel>(string, ImageReaderOptions?)

Image.Streaming.cs

Opens a file for sequential frame-by-frame decoding. Only one displayed frame of compositor state is kept in memory, regardless of the number of frames, as long as the caller disposes the frames it reads.

public static ImageReader<TPixel> OpenReader<TPixel>(string path, ImageReaderOptions? options = null) where TPixel : unmanaged
Type parameters
TPixel
The pixel type of the frames returned by the reader.
Parameters
path string
The path of the file. The reader owns the file stream and closes it when disposed.
options ImageReaderOptions?
The options, or null for ImageReaderOptions.Default.
Returns

ImageReader<TPixel> A reader positioned before the first frame, whose ImageReader<TPixel>.Info is available.

Exceptions
NotSupportedException
TPixel is not a built-in pixel struct. Thrown before any I/O.
ArgumentException
path is empty.
UnknownImageFormatException
The format is not recognized.
InvalidImageContentException
The header is malformed or truncated.
UnsupportedImageFeatureException
The file uses a recognized but unsupported feature.
ImageResourceLimitException
A configured limit is exceeded.
IOException
An I/O error occurred.

OpenReaderAsync overloads

OpenReaderAsync<TPixel>(Stream, ImageReaderOptions?, CancellationToken)

Image.Streaming.cs

Asynchronously opens a stream for sequential frame-by-frame decoding, starting at its current position.

public static Task<ImageReader<TPixel>> OpenReaderAsync<TPixel>(Stream stream, ImageReaderOptions? options = null, CancellationToken cancellationToken = default) where TPixel : unmanaged
Type parameters
TPixel
The pixel type of the frames returned by the reader.
Parameters
stream Stream
The readable source stream.
options ImageReaderOptions?
The options, or null for ImageReaderOptions.Default.
cancellationToken CancellationToken
The token to monitor for cancellation requests.
Returns

Task<ImageReader<TPixel>> A reader positioned before the first frame.

Exceptions
NotSupportedException
TPixel is not a built-in pixel struct. Thrown synchronously, before any I/O.
ArgumentException
stream is not readable.
OperationCanceledException
The operation was canceled.

OpenReaderAsync<TPixel>(string, ImageReaderOptions?, CancellationToken)

Image.Streaming.cs

Asynchronously opens a file for sequential frame-by-frame decoding.

public static Task<ImageReader<TPixel>> OpenReaderAsync<TPixel>(string path, ImageReaderOptions? options = null, CancellationToken cancellationToken = default) where TPixel : unmanaged
Type parameters
TPixel
The pixel type of the frames returned by the reader.
Parameters
path string
The path of the file. The reader owns the file stream.
options ImageReaderOptions?
The options, or null for ImageReaderOptions.Default.
cancellationToken CancellationToken
The token to monitor for cancellation requests.
Returns

Task<ImageReader<TPixel>> A reader positioned before the first frame.

Exceptions
NotSupportedException
TPixel is not a built-in pixel struct. Thrown synchronously, before any I/O.
ArgumentException
path is empty.
OperationCanceledException
The operation was canceled.

RemoveFrame(int)

Image.cs

Removes a frame. References to the removed frame become invalid and throw ObjectDisposedException on use.

public void RemoveFrame(int index)

Parameters

index int
The index of the frame to remove.

Exceptions

ArgumentOutOfRangeException
index is out of range.
InvalidOperationException
The frame is the last remaining frame, or a pixel lease is active.
ObjectDisposedException
The image is disposed.

RemovePosterFrame()

Image.cs

Removes the poster frame, if any. References to the removed poster frame become invalid.

public bool RemovePosterFrame()

Returns

bool true if a poster frame was removed; false if there was none.

Exceptions

InvalidOperationException
A pixel lease is active.
ObjectDisposedException
The image is disposed.

Save overloads

Save(Stream, ImageEncoder)

Image.cs

Encodes the image to a stream, starting at its current position. The stream is left open.

public void Save(Stream stream, ImageEncoder encoder)
Parameters
stream Stream
The writable destination stream. Seeking is never required.
encoder ImageEncoder
The encoder. Required, as a stream has no file name to infer the format from.
Exceptions
ArgumentException
stream is not writable.
UnsupportedImageFeatureException
The image cannot be encoded without a loss that the encoder settings do not allow.
IOException
An I/O error occurred.
ObjectDisposedException
The image is disposed.

Save(string, ImageEncoder?)

Image.cs

Encodes the image to a file. The file is written to a temporary file in the same directory and published only after encoding succeeds; on failure an existing file at path is left unchanged.

public void Save(string path, ImageEncoder? encoder = null)
Parameters
path string
The destination path.
encoder ImageEncoder?
The encoder, or null to select it from the file extension: .png (PNG, automatic animation mode), .apng (animated PNG), .gif (GIF), .jpg/.jpeg (JPEG), .avif (AVIF, lossless), .heic (HEIC, lossless), and the extensions of the other formats, each with default settings.
Exceptions
ArgumentException
path is empty, or encoder is null and the extension is not recognized.
UnsupportedImageFeatureException
The image cannot be encoded without a loss that the encoder settings do not allow (animation, alpha, precision, metadata).
IOException
An I/O error occurred.
ObjectDisposedException
The image is disposed.

SaveAsync overloads

SaveAsync(Stream, ImageEncoder, CancellationToken)

Image.cs

Asynchronously encodes the image to a stream, starting at its current position. The stream is left open.

public Task SaveAsync(Stream stream, ImageEncoder encoder, CancellationToken cancellationToken = default)
Parameters
stream Stream
The writable destination stream.
encoder ImageEncoder
The encoder.
cancellationToken CancellationToken
The token to monitor for cancellation requests.
Returns

Task A task that completes when the image has been written.

Exceptions
ArgumentException
stream is not writable.
UnsupportedImageFeatureException
The image cannot be encoded without a loss that the encoder settings do not allow.
OperationCanceledException
The operation was canceled.

SaveAsync(string, ImageEncoder?, CancellationToken)

Image.cs

Asynchronously encodes the image to a file, with the same atomic-publication guarantees as Image.Save.

public Task SaveAsync(string path, ImageEncoder? encoder = null, CancellationToken cancellationToken = default)
Parameters
path string
The destination path.
encoder ImageEncoder?
The encoder, or null to select it from the file extension.
cancellationToken CancellationToken
The token to monitor for cancellation requests. On cancellation, no file is published.
Returns

Task A task that completes when the file has been published.

Exceptions
ArgumentException
path is empty, or the extension is not recognized.
UnsupportedImageFeatureException
The image cannot be encoded without a loss that the encoder settings do not allow.
OperationCanceledException
The operation was canceled.

SetPosterFrame(ImageFrame)

Sets the poster frame to a copy of a frame, replacing (and invalidating) any existing poster frame. Creates default animation settings when none exist.

public abstract ImageFrame SetPosterFrame(ImageFrame source)

Parameters

source ImageFrame
The frame to copy. It must have the canvas size and the pixel format of this image.

Returns

ImageFrame The attached poster frame.

Exceptions

ArgumentException
source has a different size or pixel format.
ImageResourceLimitException
The frame would exceed the configured frame count (displayed frames plus poster) or allocation limit; the image is unchanged.
InvalidOperationException
A pixel lease of the image is active, or the source frame is leased.
ObjectDisposedException
The image or the source is disposed.

Constants

NameDescription
FormatDetectionPrefixLengthThe number of leading bytes Image.DetectFormat needs to recognize every supported format (18: the whole TGA header, which is the only format without a signature; WebP needs the 12-byte RIFF header, and PNG, GIF, JPEG and QOI are recognized from 8 bytes).

FormatDetectionPrefixLength

The number of leading bytes Image.DetectFormat needs to recognize every supported format (18: the whole TGA header, which is the only format without a signature; WebP needs the 12-byte RIFF header, and PNG, GIF, JPEG and QOI are recognized from 8 bytes).

public const int FormatDetectionPrefixLength = 18