Image Class
An owned, disposable image made of one or more full-canvas displayed frames sharing one pixel format.
public abstract class Image : IDisposableRemarks
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
| Name | Description |
|---|---|
| Animation | Gets or sets the animation-wide settings, or null for a still image. |
| Configuration | Gets the configuration captured when the image was created or loaded. |
| Frames | Gets the displayed frames, in playback order. Never empty. |
| Height | Gets the canvas height, in pixels. |
| IsAnimated | 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). |
| Metadata | Gets the mutable image-wide metadata. |
| PixelFormat | Gets the pixel format shared by every frame. |
| 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. |
| Size | Gets the canvas size, in pixels. Always positive in both dimensions. |
| Width | Gets the canvas width, in pixels. |
Animation
Image.csGets or sets the animation-wide settings, or null for a still image.
public AnimationMetadata? Animation { get; set; }Property value
Exceptions
InvalidOperationException- The value is
nullwhile 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.csGets the configuration captured when the image was created or loaded.
public ImageConfiguration Configuration { get; }Frames
Gets the displayed frames, in playback order. Never empty.
public abstract ImageFrameCollection Frames { get; }Property value
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.csIsAnimated
Image.csGets 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; }Metadata
Image.csGets the mutable image-wide metadata.
public ImageMetadata Metadata { get; }PixelFormat
Gets the pixel format shared by every frame.
public abstract PixelFormat PixelFormat { get; }Property value
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; }Size
Image.csGets the canvas size, in pixels. Always positive in both dimensions.
public Size Size { get; }Width
Image.csMethods
| Name | Description |
|---|---|
| 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
sourceImageFrame- 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
ArgumentExceptionsourcehas 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.csCreates an independent copy of the image converted to another pixel format.
public Image<TPixel> CloneAs<TPixel>(PixelConversionOptions? options = null) where TPixel : unmanagedType parameters
TPixel- The target pixel type.
Parameters
optionsPixelConversionOptions?- The conversion options, or
nullforPixelConversionOptions.Default.
Returns
Image<TPixel> A new image owned by the caller.
Exceptions
NotSupportedExceptionTPixelis 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 ofTPixelwithoutPixelConversionOptions.OutOfRangeSamplesorPixelConversionOptions.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.
Parameters
indexint- The index of the frame in
Image.Frames.
Returns
Image A new image owned by the caller.
Exceptions
ArgumentOutOfRangeExceptionindexis 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.csCreates 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 : unmanagedType parameters
TPixel- The pixel type of the frames written.
Parameters
streamStream- The writable destination stream. It is left open unless
ImageWriterOptions.LeaveOpenisfalse. optionsImageWriterOptions- The writer options.
ImageWriterOptions.Encoderis required.
Returns
ImageWriter<TPixel> A writer ready to accept the poster frame (if any) and the displayed frames.
Exceptions
NotSupportedExceptionTPixelis not a built-in pixel struct.ArgumentExceptionstreamis not writable, no encoder is specified, or the options are invalid for the encoder.
CreateWriter<TPixel>(string, ImageWriterOptions)
Image.Streaming.csCreates 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 : unmanagedType parameters
TPixel- The pixel type of the frames written.
Parameters
pathstring- The destination path.
optionsImageWriterOptions- The writer options.
ImageWriterOptions.Encodermay benullto 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
NotSupportedExceptionTPixelis not a built-in pixel struct. Thrown before any I/O.ArgumentExceptionpathis empty or has an unrecognized extension while no encoder is specified, or the options are invalid for the encoder (for example PNG withoutImageWriterOptions.ExpectedFrameCount).IOException- An I/O error occurred.
DetectFormat(ReadOnlySpan<byte>)
Image.Load.csDetects 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
prefixReadOnlySpan<byte>- The first bytes of the data. Provide at least
Image.FormatDetectionPrefixLengthbytes; a prefix shorter than 8 bytes is reported asImageFormat.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.csReleases 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,
Disposeis called from a row callback).
Draw overloads
Draw(DrawingAction, CancellationToken)
Image.Drawing.csDraws 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
actionDrawingAction- The callback that draws. It must not be asynchronous and must not retain the canvas.
cancellationTokenCancellationToken- The token to monitor for cancellation requests. It is checked by every drawing call.
Exceptions
ArgumentNullExceptionactionisnull.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.csDraws 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 structType parameters
TState- The type of the state.
Parameters
stateTState- The state passed to
action. actionDrawingAction<TState>- The callback that draws. Use a static lambda to avoid allocations. It must not retain the canvas.
cancellationTokenCancellationToken- The token to monitor for cancellation requests. It is checked by every drawing call.
Exceptions
ArgumentNullExceptionactionisnull.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.csReads 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
streamStream- The readable source stream.
optionsImageIdentifyOptions?- The options, or
nullforImageIdentifyOptions.Default.
Returns
ImageInfo The image information.
Exceptions
ArgumentExceptionstreamis 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.csReads information about in-memory encoded image data without decoding pixels.
public static ImageInfo Identify(ReadOnlySpan<byte> data, ImageIdentifyOptions? options = null)Parameters
dataReadOnlySpan<byte>- The encoded data.
optionsImageIdentifyOptions?- The options, or
nullforImageIdentifyOptions.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.csReads information about an image file without decoding its pixels.
public static ImageInfo Identify(string path, ImageIdentifyOptions? options = null)Parameters
pathstring- The path of the file.
optionsImageIdentifyOptions?- The options, or
nullforImageIdentifyOptions.Default.
Returns
ImageInfo The image information. Values that cannot be determined in the selected mode are null.
Exceptions
ArgumentExceptionpathis 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.csAsynchronously 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
streamStream- The readable source stream.
optionsImageIdentifyOptions?- The options, or
nullforImageIdentifyOptions.Default. cancellationTokenCancellationToken- The token to monitor for cancellation requests.
Returns
Task<ImageInfo> The image information.
Exceptions
ArgumentExceptionstreamis 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.csAsynchronously reads information about an image file without decoding its pixels.
public static Task<ImageInfo> IdentifyAsync(string path, ImageIdentifyOptions? options = null, CancellationToken cancellationToken = default)Parameters
pathstring- The path of the file.
optionsImageIdentifyOptions?- The options, or
nullforImageIdentifyOptions.Default. cancellationTokenCancellationToken- The token to monitor for cancellation requests.
Returns
Task<ImageInfo> The image information.
Exceptions
ArgumentExceptionpathis 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.csCreates 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 : unmanagedType parameters
TPixel- The pixel type of the source layout and of the result.
Parameters
sourceReadOnlySpan<byte>- The source bytes, row by row, top to bottom.
widthint- The width of the image. Must be positive.
heightint- The height of the image. Must be positive.
strideInBytesint- 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. configurationImageConfiguration?- The configuration of the new image, or
nullforImageConfiguration.Default.
Returns
Image<TPixel> A new image owned by the caller.
Exceptions
NotSupportedExceptionTPixelis not a built-in pixel struct.ArgumentOutOfRangeException- A dimension or the stride is invalid.
ArgumentExceptionsourceis 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.csCreates 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 : unmanagedType parameters
TPixel- The pixel type of the source and of the result.
Parameters
sourceReadOnlySpan<TPixel>- The source pixels, row by row, top to bottom.
widthint- The width of the image. Must be positive.
heightint- The height of the image. Must be positive.
strideInPixelsint- 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 leastwidth. configurationImageConfiguration?- The configuration of the new image, or
nullforImageConfiguration.Default.
Returns
Image<TPixel> A new image owned by the caller.
Exceptions
NotSupportedExceptionTPixelis not a built-in pixel struct.ArgumentOutOfRangeException- A dimension or the stride is invalid.
ArgumentExceptionsourceis too short for the dimensions and stride (the last row only needswidthpixels).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
indexint- The index at which the copy is inserted, from 0 to
Frames.Count. sourceImageFrame- 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
ArgumentOutOfRangeExceptionindexis out of range.ArgumentExceptionsourcehas 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.csDecodes 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
streamStream- The readable source stream.
optionsImageDecodeOptions?- The options, or
nullforImageDecodeOptions.Default.
Returns
Image A new image owned by the caller.
Exceptions
ArgumentExceptionstreamis 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.csDecodes 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
dataReadOnlySpan<byte>- The encoded data.
optionsImageDecodeOptions?- The options, or
nullforImageDecodeOptions.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.csDecodes 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
dataReadOnlySpan<byte>- The encoded data.
optionsImageDecodeOptions?- The options, or
nullforImageDecodeOptions.Default. cancellationTokenCancellationToken- 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.csDecodes an image file into its default pixel format (see ImageInfo.PixelFormat).
public static Image Load(string path, ImageDecodeOptions? options = null)Parameters
pathstring- The path of the file. The file is closed before the method returns.
optionsImageDecodeOptions?- The options, or
nullforImageDecodeOptions.Default.
Returns
Image A new image owned by the caller. Every displayed frame is decoded (up to ImageDecodeOptions.FrameLimit).
Exceptions
ArgumentExceptionpathis 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.csDecodes 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 : unmanagedType parameters
TPixel- The pixel type of the result.
Parameters
streamStream- The readable source stream.
optionsImageDecodeOptions?- The options, or
nullforImageDecodeOptions.Default.
Returns
Image<TPixel> A new image owned by the caller.
Exceptions
NotSupportedExceptionTPixelis not a built-in pixel struct. Thrown before any I/O.ArgumentExceptionstreamis 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.csDecodes in-memory encoded image data into the requested pixel type.
public static Image<TPixel> Load<TPixel>(ReadOnlySpan<byte> data, ImageDecodeOptions? options) where TPixel : unmanagedType parameters
TPixel- The pixel type of the result.
Parameters
dataReadOnlySpan<byte>- The encoded data.
optionsImageDecodeOptions?- The options, or
nullforImageDecodeOptions.Default.
Returns
Image<TPixel> A new image owned by the caller.
Exceptions
NotSupportedExceptionTPixelis 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.csDecodes 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 : unmanagedType parameters
TPixel- The pixel type of the result.
Parameters
dataReadOnlySpan<byte>- The encoded data.
optionsImageDecodeOptions?- The options, or
nullforImageDecodeOptions.Default. cancellationTokenCancellationToken- The token to monitor for cancellation requests.
Returns
Image<TPixel> A new image owned by the caller.
Exceptions
NotSupportedExceptionTPixelis 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.csDecodes an image file into the requested pixel type.
public static Image<TPixel> Load<TPixel>(string path, ImageDecodeOptions? options = null) where TPixel : unmanagedType parameters
TPixel- The pixel type of the result.
Parameters
pathstring- The path of the file. The file is closed before the method returns.
optionsImageDecodeOptions?- The options, or
nullforImageDecodeOptions.Default.ImageDecodeOptions.Conversioncontrols alpha removal and color profiles.
Returns
Image<TPixel> A new image owned by the caller.
Exceptions
NotSupportedExceptionTPixelis not a built-in pixel struct. Thrown before any I/O.ArgumentExceptionpathis 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.csAsynchronously 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
streamStream- The readable source stream.
optionsImageDecodeOptions?- The options, or
nullforImageDecodeOptions.Default. cancellationTokenCancellationToken- The token to monitor for cancellation requests.
Returns
Task<Image> A new image owned by the caller.
Exceptions
ArgumentExceptionstreamis 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.csAsynchronously 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
pathstring- The path of the file.
optionsImageDecodeOptions?- The options, or
nullforImageDecodeOptions.Default. cancellationTokenCancellationToken- The token to monitor for cancellation requests.
Returns
Task<Image> A new image owned by the caller.
Exceptions
ArgumentExceptionpathis empty.OperationCanceledException- The operation was canceled. No image is returned and no buffer is leaked.
LoadAsync<TPixel>(Stream, ImageDecodeOptions?, CancellationToken)
Image.Load.csAsynchronously 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 : unmanagedType parameters
TPixel- The pixel type of the result.
Parameters
streamStream- The readable source stream.
optionsImageDecodeOptions?- The options, or
nullforImageDecodeOptions.Default. cancellationTokenCancellationToken- The token to monitor for cancellation requests.
Returns
Task<Image<TPixel>> A new image owned by the caller.
Exceptions
NotSupportedExceptionTPixelis not a built-in pixel struct. Thrown synchronously, before any I/O.ArgumentExceptionstreamis not readable.OperationCanceledException- The operation was canceled.
LoadAsync<TPixel>(string, ImageDecodeOptions?, CancellationToken)
Image.Load.csAsynchronously 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 : unmanagedType parameters
TPixel- The pixel type of the result.
Parameters
pathstring- The path of the file.
optionsImageDecodeOptions?- The options, or
nullforImageDecodeOptions.Default. cancellationTokenCancellationToken- The token to monitor for cancellation requests.
Returns
Task<Image<TPixel>> A new image owned by the caller.
Exceptions
NotSupportedExceptionTPixelis not a built-in pixel struct. Thrown synchronously, before any I/O.ArgumentExceptionpathis empty.OperationCanceledException- The operation was canceled.
MoveFrame(int, int)
Image.csMoves a frame to a new position. Frame objects keep their identity.
Parameters
sourceIndexint- The current index of the frame.
destinationIndexint- 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.csOpens 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 : unmanagedType parameters
TPixel- The pixel type of the frames returned by the reader.
Parameters
streamStream- The readable source stream. It is left open unless
ImageReaderOptions.LeaveOpenisfalse. optionsImageReaderOptions?- The options, or
nullforImageReaderOptions.Default.
Returns
ImageReader<TPixel> A reader positioned before the first frame.
Exceptions
NotSupportedExceptionTPixelis not a built-in pixel struct. Thrown before any I/O.ArgumentExceptionstreamis 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.csOpens 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 : unmanagedType parameters
TPixel- The pixel type of the frames returned by the reader.
Parameters
pathstring- The path of the file. The reader owns the file stream and closes it when disposed.
optionsImageReaderOptions?- The options, or
nullforImageReaderOptions.Default.
Returns
ImageReader<TPixel> A reader positioned before the first frame, whose ImageReader<TPixel>.Info is available.
Exceptions
NotSupportedExceptionTPixelis not a built-in pixel struct. Thrown before any I/O.ArgumentExceptionpathis 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.csAsynchronously 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 : unmanagedType parameters
TPixel- The pixel type of the frames returned by the reader.
Parameters
streamStream- The readable source stream.
optionsImageReaderOptions?- The options, or
nullforImageReaderOptions.Default. cancellationTokenCancellationToken- The token to monitor for cancellation requests.
Returns
Task<ImageReader<TPixel>> A reader positioned before the first frame.
Exceptions
NotSupportedExceptionTPixelis not a built-in pixel struct. Thrown synchronously, before any I/O.ArgumentExceptionstreamis not readable.OperationCanceledException- The operation was canceled.
OpenReaderAsync<TPixel>(string, ImageReaderOptions?, CancellationToken)
Image.Streaming.csAsynchronously 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 : unmanagedType parameters
TPixel- The pixel type of the frames returned by the reader.
Parameters
pathstring- The path of the file. The reader owns the file stream.
optionsImageReaderOptions?- The options, or
nullforImageReaderOptions.Default. cancellationTokenCancellationToken- The token to monitor for cancellation requests.
Returns
Task<ImageReader<TPixel>> A reader positioned before the first frame.
Exceptions
NotSupportedExceptionTPixelis not a built-in pixel struct. Thrown synchronously, before any I/O.ArgumentExceptionpathis empty.OperationCanceledException- The operation was canceled.
RemoveFrame(int)
Image.csRemoves a frame. References to the removed frame become invalid and throw ObjectDisposedException on use.
Parameters
indexint- The index of the frame to remove.
Exceptions
ArgumentOutOfRangeExceptionindexis out of range.InvalidOperationException- The frame is the last remaining frame, or a pixel lease is active.
ObjectDisposedException- The image is disposed.
RemovePosterFrame()
Image.csRemoves 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.csEncodes the image to a stream, starting at its current position. The stream is left open.
public void Save(Stream stream, ImageEncoder encoder)Parameters
streamStream- The writable destination stream. Seeking is never required.
encoderImageEncoder- The encoder. Required, as a stream has no file name to infer the format from.
Exceptions
ArgumentExceptionstreamis 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.csEncodes 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
pathstring- The destination path.
encoderImageEncoder?- The encoder, or
nullto 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
ArgumentExceptionpathis empty, orencoderisnulland 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.csAsynchronously 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
streamStream- The writable destination stream.
encoderImageEncoder- The encoder.
cancellationTokenCancellationToken- The token to monitor for cancellation requests.
Returns
Task A task that completes when the image has been written.
Exceptions
ArgumentExceptionstreamis 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.csAsynchronously 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
pathstring- The destination path.
encoderImageEncoder?- The encoder, or
nullto select it from the file extension. cancellationTokenCancellationToken- 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
ArgumentExceptionpathis 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
sourceImageFrame- The frame to copy. It must have the canvas size and the pixel format of this image.
Returns
ImageFrame The attached poster frame.
Exceptions
ArgumentExceptionsourcehas 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
| Name | Description |
|---|---|
| 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). |
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