Table of Contents

Class Raster

Namespace
Egami
Assembly
Egami.dll

Measuring images: comparison, statistics, histograms, colors and a pixel signature. Nothing here changes a raster.

public abstract class Raster : IDisposable
Inheritance
Raster
Implements
Derived
Raster<TPixel>
Inherited Members

Examples

// Load in the pixel type that best fits the file (here Rgba8: this PNG stores alpha).
using Raster image = Raster.Load("duck.png");
Console.WriteLine($"{image.Width} × {image.Height}, {image.Layout.ChannelOrder}");

// Make a thumbnail that fits 200 × 200, keeping the aspect ratio, and save it as JPEG.
image.Apply(ops => ops.Fit(200, 200));
image.Save("duck-small.jpg");

Remarks

A raster is not thread-safe. Several threads may read it at once, but nothing may read while another thread writes. Methods that return a new raster say so in their name (Copy, As); everything else works in place.

Properties

Context

Gets the context the raster allocates from: its memory source, limits and MaxParallelism, for code outside Egami that works on the raster's pixels, such as a canvas drawing onto it.

public EgamiContext Context { get; }

Property Value

EgamiContext

FrameCount

Gets the number of frames. Always at least 1.

public abstract int FrameCount { get; }

Property Value

int

Height

Gets the height in pixels.

public int Height { get; }

Property Value

int

Layout

Gets the memory layout of the pixel type.

public abstract PixelLayoutInfo Layout { get; }

Property Value

PixelLayoutInfo

Metadata

Gets the raster's metadata.

public RasterMetadata Metadata { get; }

Property Value

RasterMetadata

Width

Gets the width in pixels.

public int Width { get; }

Property Value

int

Methods

Append(IReadOnlyList<Raster>, Axis, int, Rgba8, Alignment)

Returns the images side by side or stacked, as ImageMagick's +append and -append do with -gravity: each image's first frame in order, with spacing pixels between them, aligned across the strip and with background around the smaller ones.

public static Raster Append(IReadOnlyList<Raster> images, Axis axis = Axis.Horizontal, int spacing = 0, Rgba8 background = default, Alignment alignment = Alignment.Start)

Parameters

images IReadOnlyList<Raster>

At least one raster, of any sizes and pixel types.

axis Axis

Side by side (the default) or stacked.

spacing int

The gap between neighbours, in pixels, 0 or more.

background Rgba8

The color of gaps and of the space around smaller images; transparent black by default.

alignment Alignment

Where smaller images sit across the strip.

Returns

Raster

The strip, with the first raster's pixel type, metadata and color profile; other images are converted to them. The caller must dispose it.

Examples

// Side by side with a 10-pixel white gap, the shorter image centered vertically (ImageMagick's +append).
using Raster strip = Raster.Append([duck, egret], Axis.Horizontal, spacing: 10, background: Rgba8.White, alignment: Alignment.Center);

// Stacked, as -append does.
using Raster column = Raster.Append([duck, egret], Axis.Vertical);

Exceptions

ArgumentNullException

images or one of them is null.

ArgumentException

images is empty.

ArgumentOutOfRangeException

The spacing is negative or an enum is not defined.

LimitExceededException

The result would break MaxTotalBytes.

Apply(Action<RasterOps>, CancellationToken)

Runs a chain of operations on every frame, changing this raster in place. See Apply(Action<RasterOps>, CancellationToken).

public void Apply(Action<RasterOps> build, CancellationToken cancellationToken = default)

Parameters

build Action<RasterOps>

Records the chain.

cancellationToken CancellationToken

Cancels between steps and between bands of rows.

Exceptions

ArgumentNullException

build is null.

ArgumentException

A step would make the size less than 1.

ArgumentOutOfRangeException

A crop, pad or fill rectangle does not fit the image when the chain runs.

LimitExceededException

The pixels the chain needs would break MaxTotalBytes.

ObjectDisposedException

The raster has been disposed.

OperationCanceledException

cancellationToken was canceled.

As<TTo>()

Returns a new raster with every frame converted to TTo. See Convert<TFrom, TTo>(ReadOnlySpan<TFrom>, Span<TTo>).

public Raster<TTo> As<TTo>() where TTo : unmanaged, IPixelType<TTo>

Returns

Raster<TTo>

The new raster. The caller must dispose it.

Type Parameters

TTo

The pixel type to convert to.

Exceptions

ObjectDisposedException

The raster has been disposed.

ColorMask(Rgba8, float)

Returns a mask of the first frame: 255 where a pixel lies within tolerance of color, 0 elsewhere, by ImageMagick's -fuzz distance. Use it to select by color, then edit only the selection.

public Raster<Gray8> ColorMask(Rgba8 color, float tolerance = 0)

Parameters

color Rgba8

The color to select, with its alpha.

tolerance float

The color distance, from 0 (the exact color) to 1 (every color).

Returns

Raster<Gray8>

The mask, the raster's size. The caller must dispose it.

Examples

// Select by color, then edit only the selection: a magic wand from a point, and every pixel close to a color.
using Raster<Gray8> wand = photo.FloodMask(new Point(30, 30), tolerance: 0.12f);
using Raster<Gray8> reds = photo.ColorMask(new Rgba8(200, 40, 30, 255), tolerance: 0.2f);
photo.Apply(ops => ops
    .Within(new Mask(wand), o => o.Blur(4))
    .Within(new Mask(reds), o => o.Saturation(1.4f)), Ct);

Exceptions

ArgumentOutOfRangeException

tolerance is outside 0..1.

ObjectDisposedException

The raster has been disposed.

CombineChannels<TPixel>(Raster, Raster, Raster, Raster?)

Builds a raster from three or four rasters of the same size, reading each one's gray value (the luminance of a color raster, the alpha of an Alpha8 raster) as red, green, blue and alpha. Without alpha the result is opaque. Frame counts must match, or be 1, which is then used for every frame. The result takes red's metadata and frame metadata, with the sRGB profile.

public static Raster<TPixel> CombineChannels<TPixel>(Raster red, Raster green, Raster blue, Raster? alpha = null) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

red Raster

The red channel.

green Raster

The green channel.

blue Raster

The blue channel.

alpha Raster

The alpha channel, or null for opaque.

Returns

Raster<TPixel>

The new raster. The caller must dispose it.

Type Parameters

TPixel

The pixel type of the result.

Examples

// Pull channels out as gray rasters (Gray8 from 8-bit images), edit one, and build the image again.
using Raster red = photo.ExtractChannel(ColorChannel.Red);
using Raster green = photo.ExtractChannel(ColorChannel.Green);
using Raster blue = photo.ExtractChannel(ColorChannel.Blue);
blue.Apply(ops => ops.Blur(2), Ct);
using Raster<Rgba8> rebuilt = Raster.CombineChannels<Rgba8>(red, green, blue);

Exceptions

ArgumentNullException

A color channel is null.

ArgumentException

The rasters differ in size, or in frame count other than 1.

Compare(Raster, Raster, CompareOptions?)

Compares two images of the same size and returns every cheap metric at once, per channel and overall: mean absolute and mean squared error, RMSE, PSNR, the peak error and how many pixels differ, all on the 0 to 1 scale, with SSIM on request. The images may have different pixel types: an Rgb8 and an Rgba8 copy of one picture compare as identical. Color profiles are not reconciled, so convert both to one with ConvertColor<TTo>(ColorProfile, ColorTransformOptions?) first when they differ.

public static CompareResult Compare(Raster a, Raster b, CompareOptions? options = null)

Parameters

a Raster

The first image.

b Raster

The second image, the same size.

options CompareOptions

The alpha treatment, fuzz, SSIM, region and frame, or null for Default.

Returns

CompareResult

The differences.

Examples

// Every cheap metric in one pass, per channel and overall, on the 0 to 1 scale; SSIM on request.
CompareResult result = Raster.Compare(expected, actual, new CompareOptions { Ssim = true, Fuzz = 0.02f });
Console.WriteLine($"PSNR {result.Overall.Psnr:F1} dB, SSIM {result.Overall.Ssim:F4}, {result.DifferentPixels} pixels off by more than 2%");
bool sameLook = result.Overall.Psnr >= 40;

Exceptions

ArgumentNullException

a or b is null.

ArgumentException

The images differ in size.

ArgumentOutOfRangeException

The frame is missing from an image, or the region leaves the image.

ObjectDisposedException

An image has been disposed.

ConvertColor<TTo>(ColorProfile, ColorTransformOptions?)

Returns a new raster of TTo with every frame converted from the encoding this raster is in (GetColorProfile()) to target, and metadata that says so. This is how a CMYK image becomes RGB through its profile, or RGB becomes CMYK for print; As<TTo>() converts numerically instead.

public Raster<TTo> ConvertColor<TTo>(ColorProfile target, ColorTransformOptions? options = null) where TTo : unmanaged, IPixelType<TTo>

Parameters

target ColorProfile

The encoding to convert to.

options ColorTransformOptions

The intent and black point compensation, or null for the defaults.

Returns

Raster<TTo>

The new raster. The caller must dispose it.

Type Parameters

TTo

The pixel type to convert to. Its model need not be the target's: see ColorTransform.

Examples

// A CMYK image becomes RGB through its profile (or the plain formula if it has none), as a new raster.
using Raster<Cmyk8> print = Raster.Load<Cmyk8>(path);
using Raster<Rgb8> screen = print.ConvertColor<Rgb8>(ColorProfile.Srgb, new ColorTransformOptions { Intent = RenderingIntent.RelativeColorimetric, BlackPointCompensation = true });

Exceptions

ArgumentNullException

target is null.

ObjectDisposedException

The raster has been disposed.

UnsupportedFormatException

The target is an ICC profile with no tables for converting to it.

CountColors(int)

Counts the distinct stored colors of a frame, exactly, as ImageMagick's %k does. Each distinct stored value counts, so two float pixels that differ in the last bit are two colors. Types of up to 3 bytes use a 2 MB table; wider ones keep a set of the colors seen, which counts against MaxTotalBytes at its worst case (every pixel distinct).

public long CountColors(int frame = 0)

Parameters

frame int

The frame, 0 (the default) for the first.

Returns

long

The number of distinct colors.

Examples

// Unique colors, the palette of a small image, and quick checks before choosing an output format.
long count = photo.CountColors();
IReadOnlyList<Rgba16>? palette = photo.GetColors(256);   // null: more than 256 colors
bool needsAlpha = !photo.IsOpaque();
bool grayscale = photo.IsGray(tolerance: 1 / 255f);

Exceptions

ArgumentOutOfRangeException

frame is not a frame of the image.

LimitExceededException

The set could break MaxTotalBytes.

ObjectDisposedException

The raster has been disposed.

Create<TPixel>(int, int, EgamiContext?)

Creates a raster with one frame, with every byte zero (transparent black for types with alpha).

public static Raster<TPixel> Create<TPixel>(int width, int height, EgamiContext? context = null) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

width int

The width in pixels, at least 1.

height int

The height in pixels, at least 1.

context EgamiContext

The context to allocate from, or null for Default.

Returns

Raster<TPixel>

The new raster. The caller must dispose it.

Type Parameters

TPixel

The pixel type.

Exceptions

ArgumentOutOfRangeException

width or height is less than 1.

Create<TPixel>(int, int, TPixel, EgamiContext?)

Creates a raster with one frame, filled with one color.

public static Raster<TPixel> Create<TPixel>(int width, int height, TPixel fill, EgamiContext? context = null) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

width int

The width in pixels, at least 1.

height int

The height in pixels, at least 1.

fill TPixel

The color of every pixel.

context EgamiContext

The context to allocate from, or null for Default.

Returns

Raster<TPixel>

The new raster. The caller must dispose it.

Type Parameters

TPixel

The pixel type.

Exceptions

ArgumentOutOfRangeException

width or height is less than 1.

Derive(Action<RasterOps>, CancellationToken)

Runs a chain of operations and returns the result as a new raster. See Derive(Action<RasterOps>, CancellationToken).

public Raster Derive(Action<RasterOps> build, CancellationToken cancellationToken = default)

Parameters

build Action<RasterOps>

Records the chain.

cancellationToken CancellationToken

Cancels between steps and between bands of rows.

Returns

Raster

The new raster, in the same pixel type. The caller must dispose it.

Exceptions

ArgumentNullException

build is null.

ArgumentException

A step would make the size less than 1.

ArgumentOutOfRangeException

A crop, pad or fill rectangle does not fit the image when the chain runs.

LimitExceededException

The pixels the chain needs would break MaxTotalBytes.

ObjectDisposedException

The raster has been disposed.

OperationCanceledException

cancellationToken was canceled.

DetectSkew(float)

Returns the tilt of the first frame's text lines or other strong horizontal structure, in degrees clockwise, to 0.05°: Deskew(float, Rgba8?, bool, ResampleFilter) turns the image back by it. A gray copy about 1,500 pixels on its long side is binarized with Otsu's threshold and every angle up to maxAngle is scored by how sharply the ink's projection piles up in rows (Postl's projection-profile method).

public float DetectSkew(float maxAngle = 15)

Parameters

maxAngle float

The largest tilt looked for, in degrees, more than 0 and at most 45.

Returns

float

The tilt, or 0 when no angle stands out clearly from level (a picture, noise, or an already straight page).

Examples

// Measure the tilt first, if you want to show it or decide yourself...
float tilt = photo.DetectSkew(maxAngle: 10);

// ...or straighten in one step, keeping the page size with white corners.
using Raster straight = photo.Derive(ops => ops.Deskew(background: Rgba8.White), Ct);

Exceptions

ArgumentOutOfRangeException

maxAngle is out of range.

ObjectDisposedException

The raster has been disposed.

Difference(Raster, Raster, DifferenceStyle, DifferenceOptions?)

Returns a picture of where two images of the same size differ: Highlight marks differing pixels in red over a faded copy of a, as ImageMagick's compare does, and Absolute shows |a − b| per channel. The result has a's pixel type and size.

public static Raster Difference(Raster a, Raster b, DifferenceStyle style = DifferenceStyle.Highlight, DifferenceOptions? options = null)

Parameters

a Raster

The first image.

b Raster

The second image, the same size.

style DifferenceStyle

What to draw. Defaults to Highlight.

options DifferenceOptions

The colors, fuzz, factor and frame, or null for Default.

Returns

Raster

The picture, one frame. The caller must dispose it.

Examples

// ImageMagick compare's red-over-faded picture, and the plain per-channel difference turned up 8 times.
using Raster highlight = Raster.Difference(a, b);
using Raster gaps = Raster.Difference(a, b, DifferenceStyle.Absolute, new DifferenceOptions { Amplify = 8 });
highlight.Save("highlight.png");
gaps.Save("gaps.png");

Exceptions

ArgumentNullException

a or b is null.

ArgumentException

The images differ in size.

ArgumentOutOfRangeException

style is not defined, or the frame is missing.

ObjectDisposedException

An image has been disposed.

Dispose()

Returns the raster's memory to its source. Calling it again does nothing.

public void Dispose()

Dispose(bool)

Releases the frames' memory.

protected abstract void Dispose(bool disposing)

Parameters

disposing bool

true when called from Dispose().

DominantColors(int, DominantColorOptions?)

Returns the main colors of the first frame with the share of pixels each stands for, largest first: k-means in Oklab on a sample of at most MaxSamples pixels, seeded with Wu's palette so the answer is the same every run, with near-identical clusters merged. Transparent pixels are left out.

public IReadOnlyList<WeightedColor> DominantColors(int count = 5, DominantColorOptions? options = null)

Parameters

count int

The most colors wanted, 1 to 128. Defaults to 5. Fewer come back when the image has fewer distinct colors.

options DominantColorOptions

The sampling, passes and merging, or null for Default.

Returns

IReadOnlyList<WeightedColor>

The colors, largest share first; empty when every pixel is transparent.

Examples

// The main colors and how much of the picture each covers, e.g. to pick brand colors from a logo or a placeholder color.
IReadOnlyList<WeightedColor> colors = logo.DominantColors(5);
foreach ((Rgba8 color, double weight) in colors)
{
    Console.WriteLine($"#{color.R:X2}{color.G:X2}{color.B:X2} covers {weight:P0}");
}

Exceptions

ArgumentOutOfRangeException

count is outside 1 to 128.

ObjectDisposedException

The raster has been disposed.

EntropyBounds(float)

Returns the rectangle EntropyCrop(float) would keep: the union over the frames of the 16 × 16 tiles whose luminance entropy reaches threshold.

public Rect EntropyBounds(float threshold = 0.5)

Parameters

threshold float

The entropy a tile needs, from 0 to 1.

Returns

Rect

The rectangle, or an empty one when no tile reaches the threshold.

Examples

// Keep the part with detail in it: flat tiles (a plain backdrop) fall away.
Rect busy = padded.EntropyBounds();
using Raster<Rgba8> cropped = padded.Derive(ops => ops.EntropyCrop(), Ct);

Exceptions

ArgumentOutOfRangeException

threshold is outside 0..1.

ObjectDisposedException

The raster has been disposed.

ExtractChannel(ColorChannel)

Returns a new gray raster holding one channel of every frame: Gray8 from 8-bit pixel types, Gray16 from 16-bit ones, GrayF32 from half and float ones. A gray raster's red, green and blue are its gray value; a raster without alpha gives an all-white alpha. Resolution and EXIF are kept; the ICC profile is dropped, as one channel of a color image is not a gray image in any profile.

public Raster ExtractChannel(ColorChannel channel)

Parameters

channel ColorChannel

The channel. Luminance is 0.2126 R + 0.7152 G + 0.0722 B of the stored values.

Returns

Raster

The new raster. The caller must dispose it.

Examples

// Pull channels out as gray rasters (Gray8 from 8-bit images), edit one, and build the image again.
using Raster red = photo.ExtractChannel(ColorChannel.Red);
using Raster green = photo.ExtractChannel(ColorChannel.Green);
using Raster blue = photo.ExtractChannel(ColorChannel.Blue);
blue.Apply(ops => ops.Blur(2), Ct);
using Raster<Rgba8> rebuilt = Raster.CombineChannels<Rgba8>(red, green, blue);

Exceptions

ArgumentOutOfRangeException

channel is not defined.

ObjectDisposedException

The raster has been disposed.

ExtractChannel<TPixel>(ColorChannel)

Returns a new raster of TPixel holding one channel of every frame as its gray value, as ExtractChannel(ColorChannel) does, converted to the type asked for.

public Raster<TPixel> ExtractChannel<TPixel>(ColorChannel channel) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

channel ColorChannel

The channel.

Returns

Raster<TPixel>

The new raster. The caller must dispose it.

Type Parameters

TPixel

The pixel type of the result, usually a gray type.

Examples

// Pull channels out as gray rasters (Gray8 from 8-bit images), edit one, and build the image again.
using Raster red = photo.ExtractChannel(ColorChannel.Red);
using Raster green = photo.ExtractChannel(ColorChannel.Green);
using Raster blue = photo.ExtractChannel(ColorChannel.Blue);
blue.Apply(ops => ops.Blur(2), Ct);
using Raster<Rgba8> rebuilt = Raster.CombineChannels<Rgba8>(red, green, blue);

Exceptions

ArgumentOutOfRangeException

channel is not defined.

ObjectDisposedException

The raster has been disposed.

FindThreshold(ThresholdMethod, ThresholdMode)

Returns the level AutoThreshold(ThresholdMethod, ThresholdMode, Rgba8?, Rgba8?, bool) would use, from 0 to 1, found by method in a 256-bin histogram of every frame, as ImageMagick's -auto-threshold finds it; 0.5 for an image of one value.

public float FindThreshold(ThresholdMethod method = ThresholdMethod.Otsu, ThresholdMode mode = ThresholdMode.Luminance)

Parameters

method ThresholdMethod

How the level is found. Defaults to Otsu.

mode ThresholdMode

What is measured; Channels measures red, green and blue together. Defaults to Luminance.

Returns

float

The level.

Examples

// Threshold a scanned page for OCR: Otsu's level for an evenly lit page, or Bradley's local threshold for uneven light.
float level = page.FindThreshold(ThresholdMethod.Otsu);
using Raster<Gray8> even = page.Derive(o => o.AutoThreshold(ThresholdMethod.Otsu), Ct);
using Raster<Gray8> uneven = page.Derive(o => o.AdaptiveThreshold(limit: 0.15f), Ct);

Exceptions

ArgumentOutOfRangeException

An enum value is not defined.

ObjectDisposedException

The raster has been disposed.

FloodMask(Point, float, Connectivity)

Returns a mask of the first frame's region connected to seed whose colors lie within tolerance of the seed's: the "magic wand". 255 inside the region, 0 elsewhere.

public Raster<Gray8> FloodMask(Point seed, float tolerance = 0, Connectivity connectivity = Connectivity.Four)

Parameters

seed Point

Where the region starts.

tolerance float

The color distance, from 0 (the seed's exact color) to 1 (every color).

connectivity Connectivity

Whether the region spreads to the four side neighbours or also the four diagonal ones.

Returns

Raster<Gray8>

The mask, the raster's size. The caller must dispose it.

Examples

// Select by color, then edit only the selection: a magic wand from a point, and every pixel close to a color.
using Raster<Gray8> wand = photo.FloodMask(new Point(30, 30), tolerance: 0.12f);
using Raster<Gray8> reds = photo.ColorMask(new Rgba8(200, 40, 30, 255), tolerance: 0.2f);
photo.Apply(ops => ops
    .Within(new Mask(wand), o => o.Blur(4))
    .Within(new Mask(reds), o => o.Saturation(1.4f)), Ct);

Exceptions

ArgumentOutOfRangeException

The seed lies outside the raster, tolerance is outside 0..1, or connectivity is not defined.

ObjectDisposedException

The raster has been disposed.

GetColors(int, int)

Returns the distinct colors of a frame, as 16-bit colors in ascending order, when there are at most limit.

public IReadOnlyList<Rgba16>? GetColors(int limit, int frame = 0)

Parameters

limit int

The most colors wanted; the scan stops once there are more.

frame int

The frame, 0 (the default) for the first.

Returns

IReadOnlyList<Rgba16>

The colors, or null when there are more than limit.

Examples

// Unique colors, the palette of a small image, and quick checks before choosing an output format.
long count = photo.CountColors();
IReadOnlyList<Rgba16>? palette = photo.GetColors(256);   // null: more than 256 colors
bool needsAlpha = !photo.IsOpaque();
bool grayscale = photo.IsGray(tolerance: 1 / 255f);

Exceptions

ArgumentOutOfRangeException

limit is negative, or frame is not a frame of the image.

ObjectDisposedException

The raster has been disposed.

Grid(IReadOnlyList<Raster>, int, Size?, int, Rgba8, ResampleFilter)

Returns a contact sheet, as ImageMagick's montage with -tile and -geometry makes one: the images' first frames in rows of columns cells, each image shrunk to fit its cell if it is larger and centered in it.

public static Raster Grid(IReadOnlyList<Raster> images, int columns, Size? cell = null, int spacing = 0, Rgba8 background = default, ResampleFilter filter = ResampleFilter.Bicubic)

Parameters

images IReadOnlyList<Raster>

At least one raster, of any sizes and pixel types.

columns int

The cells per row, at least 1.

cell Size?

The cell size, or null (the default) for the largest image's width and height.

spacing int

The gap between cells, in pixels, 0 or more.

background Rgba8

The color of gaps and empty cell space; transparent black by default.

filter ResampleFilter

The kernel images are shrunk with.

Returns

Raster

The sheet, with the first raster's pixel type, metadata and color profile. The caller must dispose it.

Examples

// A contact sheet three cells wide; each photo shrinks to fit a 200 × 200 cell and sits in its middle.
using Raster sheet = Raster.Grid(photos, columns: 3, cell: new Size(200, 200), spacing: 8, background: Rgba8.White);

Exceptions

ArgumentNullException

images or one of them is null.

ArgumentException

images is empty.

ArgumentOutOfRangeException

A count or size is out of range, or the filter is not defined.

LimitExceededException

The result would break MaxTotalBytes.

HaldIdentity(int)

Creates the identity Hald CLUT image of level: level³ × level³ pixels holding a (level²)³ table that changes nothing, red fastest, as ImageMagick's hald:8. Grade it in any editor, then load it back with FromHald(Raster).

public static Raster<Rgba8> HaldIdentity(int level = 8)

Parameters

level int

The level, from 2 to 16. Defaults to 8 (512 × 512, a 64³ table).

Returns

Raster<Rgba8>

The image; the caller disposes it.

Examples

// Export the identity Hald image, grade it in any editor, and load the graded image back as a table.
using Raster<Rgba8> identity = Raster.HaldIdentity(level: 8);   // 512 × 512, a 64³ table
identity.Save("hald.png");

using Raster graded = Raster.Load("hald.png");
Lut3D fromHald = Lut3D.FromHald(graded);
using Raster<Rgba16> back = fromHald.ToHald(level: 8);

Exceptions

ArgumentOutOfRangeException

level is outside 2 to 16.

HaldIdentity<TPixel>(int)

Creates the identity Hald CLUT image of level in TPixel, such as Rgba16 for 16-bit grading.

public static Raster<TPixel> HaldIdentity<TPixel>(int level = 8) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

level int

The level, from 2 to 16. Defaults to 8.

Returns

Raster<TPixel>

The image; the caller disposes it.

Type Parameters

TPixel

The pixel type.

Examples

// Export the identity Hald image, grade it in any editor, and load the graded image back as a table.
using Raster<Rgba8> identity = Raster.HaldIdentity(level: 8);   // 512 × 512, a 64³ table
identity.Save("hald.png");

using Raster graded = Raster.Load("hald.png");
Lut3D fromHald = Lut3D.FromHald(graded);
using Raster<Rgba16> back = fromHald.ToHald(level: 8);

Exceptions

ArgumentOutOfRangeException

level is outside 2 to 16.

Histogram(ColorChannel, int, int)

Counts how many pixels of a frame fall into each of bins equal ranges of one channel's values.

public Histogram Histogram(ColorChannel channel, int bins = 256, int frame = 0)

Parameters

channel ColorChannel

The channel, or Luminance for the Rec. 709 luma.

bins int

The number of bins, 2 to 65,536. Defaults to 256, one per 8-bit value.

frame int

The frame, 0 (the default) for the first.

Returns

Histogram

The histogram.

Examples

// How the brightness is spread: 256 bins, and the levels below which 1% and 99% of the pixels lie.
Histogram histogram = photo.Histogram(ColorChannel.Luminance);
double shadows = histogram.Percentile(0.01), highlights = histogram.Percentile(0.99);
long midtones = histogram.Counts.Skip(64).Take(128).Sum();

Exceptions

ArgumentOutOfRangeException

An argument is out of range or not defined.

ObjectDisposedException

The raster has been disposed.

IsGray(float, int)

Returns whether every pixel is gray: its red, green and blue lie within tolerance of each other, as ImageMagick's Grayscale type with -fuzz. It stops at the first pixel that is not, and answers at once for gray pixel types.

public bool IsGray(float tolerance = 0, int frame = -1)

Parameters

tolerance float

How far apart the channels may be, from 0 (equal) to 1.

frame int

The frame, or -1 (the default) for every frame.

Returns

bool

true when every pixel is gray.

Examples

// Unique colors, the palette of a small image, and quick checks before choosing an output format.
long count = photo.CountColors();
IReadOnlyList<Rgba16>? palette = photo.GetColors(256);   // null: more than 256 colors
bool needsAlpha = !photo.IsOpaque();
bool grayscale = photo.IsGray(tolerance: 1 / 255f);

Exceptions

ArgumentOutOfRangeException

An argument is out of range.

ObjectDisposedException

The raster has been disposed.

IsOpaque(int)

Returns whether every pixel is fully opaque. It stops at the first pixel that is not, and answers at once for pixel types without alpha.

public bool IsOpaque(int frame = -1)

Parameters

frame int

The frame, or -1 (the default) for every frame.

Returns

bool

true when no pixel has alpha below 1.

Examples

// Unique colors, the palette of a small image, and quick checks before choosing an output format.
long count = photo.CountColors();
IReadOnlyList<Rgba16>? palette = photo.GetColors(256);   // null: more than 256 colors
bool needsAlpha = !photo.IsOpaque();
bool grayscale = photo.IsGray(tolerance: 1 / 255f);

Exceptions

ArgumentOutOfRangeException

frame is not -1 or a frame of the image.

ObjectDisposedException

The raster has been disposed.

Load(Stream, EgamiContext?, ReaderOptions?)

Detects the format from the first bytes and decodes the image in the pixel type that best fits it, such as Rgb8 for a color image without alpha or Gray16 for a 16-bit gray one.

public static Raster Load(Stream stream, EgamiContext? context = null, ReaderOptions? options = null)

Parameters

stream Stream

The encoded image. It is read from its current position and left open; a seekable stream ends just past the image.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read, or null for Default.

Returns

Raster

The raster. The caller must dispose it.

Examples

// Load in the pixel type that best fits the file (here Rgba8: this PNG stores alpha).
using Raster image = Raster.Load("duck.png");
Console.WriteLine($"{image.Width} × {image.Height}, {image.Layout.ChannelOrder}");

// Make a thumbnail that fits 200 × 200, keeping the aspect ratio, and save it as JPEG.
image.Apply(ops => ops.Fit(200, 200));
image.Save("duck-small.jpg");

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

The image breaks a safety limit.

ArgumentNullException

stream is null.

Load(Stream, FormatInfo, EgamiContext?, ReaderOptions?)

Decodes an image of a known format without detecting it, for data that has no signature of its own, such as a JBIG2 stream embedded in a PDF. Otherwise as Load(Stream, EgamiContext?, ReaderOptions?).

public static Raster Load(Stream stream, FormatInfo format, EgamiContext? context = null, ReaderOptions? options = null)

Parameters

stream Stream

The encoded image. It is read from its current position and left open; a seekable stream ends just past the image.

format FormatInfo

The format to read with. It need not be registered in the context.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read, or null for Default.

Returns

Raster

The raster. The caller must dispose it.

Examples

// Data without a signature of its own (a TGA here; a JBIG2 stream from a PDF) loads with its format named,
// which skips detection. Probe, LoadAll and RasterDecoder.Open take the format the same way.
using Raster image = Raster.Load(data, TgaFormat.Info);
RasterInfo info = Raster.Probe(data, TgaFormat.Info);

Exceptions

UnsupportedFormatException

format has no reader.

CorruptDataException

The data breaks the format's rules, including data of another format.

LimitExceededException

The image breaks a safety limit.

ArgumentNullException

stream or format is null.

Load(ReadOnlyMemory<byte>, EgamiContext?, ReaderOptions?)

Loads an image from bytes in memory. See Load(Stream, EgamiContext?, ReaderOptions?).

public static Raster Load(ReadOnlyMemory<byte> data, EgamiContext? context = null, ReaderOptions? options = null)

Parameters

data ReadOnlyMemory<byte>

The encoded image.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read, or null for Default.

Returns

Raster

The raster. The caller must dispose it.

Examples

// Load in the pixel type that best fits the file (here Rgba8: this PNG stores alpha).
using Raster image = Raster.Load("duck.png");
Console.WriteLine($"{image.Width} × {image.Height}, {image.Layout.ChannelOrder}");

// Make a thumbnail that fits 200 × 200, keeping the aspect ratio, and save it as JPEG.
image.Apply(ops => ops.Fit(200, 200));
image.Save("duck-small.jpg");

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

The image breaks a safety limit.

Load(ReadOnlyMemory<byte>, FormatInfo, EgamiContext?, ReaderOptions?)

Decodes an image of a known format from bytes in memory. See Load(Stream, FormatInfo, EgamiContext?, ReaderOptions?).

public static Raster Load(ReadOnlyMemory<byte> data, FormatInfo format, EgamiContext? context = null, ReaderOptions? options = null)

Parameters

data ReadOnlyMemory<byte>

The encoded image.

format FormatInfo

The format to read with. It need not be registered in the context.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read, or null for Default.

Returns

Raster

The raster. The caller must dispose it.

Examples

// Data without a signature of its own (a TGA here; a JBIG2 stream from a PDF) loads with its format named,
// which skips detection. Probe, LoadAll and RasterDecoder.Open take the format the same way.
using Raster image = Raster.Load(data, TgaFormat.Info);
RasterInfo info = Raster.Probe(data, TgaFormat.Info);

Exceptions

UnsupportedFormatException

format has no reader.

CorruptDataException

The data breaks the format's rules, including data of another format.

LimitExceededException

The image breaks a safety limit.

ArgumentNullException

format is null.

Load(string, EgamiContext?, ReaderOptions?)

public static Raster Load(string path, EgamiContext? context = null, ReaderOptions? options = null)

Parameters

path string

The file path.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read, or null for Default.

Returns

Raster

The raster. The caller must dispose it.

Examples

// Load in the pixel type that best fits the file (here Rgba8: this PNG stores alpha).
using Raster image = Raster.Load("duck.png");
Console.WriteLine($"{image.Width} × {image.Height}, {image.Layout.ChannelOrder}");

// Make a thumbnail that fits 200 × 200, keeping the aspect ratio, and save it as JPEG.
image.Apply(ops => ops.Fit(200, 200));
image.Save("duck-small.jpg");

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

The image breaks a safety limit.

ArgumentNullException

path is null.

FileNotFoundException

The file does not exist.

IOException

The file cannot be read.

LoadAll(Stream, EgamiContext?, ReaderOptions?)

Loads every image of a file, each in the pixel type that best fits it: every full-resolution page of a TIFF, the one image of any other format. Each image is loaded as Load(Stream, EgamiContext?, ReaderOptions?) would load it, so the options apply to each.

public static RasterList LoadAll(Stream stream, EgamiContext? context = null, ReaderOptions? options = null)

Parameters

stream Stream

The encoded file. It is read from its current position and left open; a stream that cannot seek is read whole first.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read each image, or null for Default.

Returns

RasterList

The images, in the file's order. The caller must dispose the list, which disposes them.

Examples

// Every page at its own size and pixel type. The list owns the rasters.
using RasterList pages = Raster.LoadAll("scan.tif");
foreach (Raster page in pages)
{
    Console.WriteLine($"{page.Width} × {page.Height}");
}

// Keep one page after the list is gone.
using Raster first = pages.Detach(0);

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

An image breaks a safety limit, there are more than MaxFrames, or together they pass MaxTotalBytes.

ArgumentNullException

stream is null.

LoadAll(Stream, FormatInfo, EgamiContext?, ReaderOptions?)

Loads every image of a file of a known format. See LoadAll(Stream, EgamiContext?, ReaderOptions?).

public static RasterList LoadAll(Stream stream, FormatInfo format, EgamiContext? context = null, ReaderOptions? options = null)

Parameters

stream Stream

The encoded file.

format FormatInfo

The format to read with. It need not be registered in the context.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read each image, or null for Default.

Returns

RasterList

The images, in the file's order. The caller must dispose the list.

Examples

// Data without a signature of its own (a TGA here; a JBIG2 stream from a PDF) loads with its format named,
// which skips detection. Probe, LoadAll and RasterDecoder.Open take the format the same way.
using Raster image = Raster.Load(data, TgaFormat.Info);
RasterInfo info = Raster.Probe(data, TgaFormat.Info);

Exceptions

UnsupportedFormatException

format has no reader.

CorruptDataException

The data breaks the format's rules, including data of another format.

LimitExceededException

An image or the images together break a safety limit.

ArgumentNullException

stream or format is null.

LoadAll(ReadOnlyMemory<byte>, EgamiContext?, ReaderOptions?)

Loads every image of a file in memory. See LoadAll(Stream, EgamiContext?, ReaderOptions?).

public static RasterList LoadAll(ReadOnlyMemory<byte> data, EgamiContext? context = null, ReaderOptions? options = null)

Parameters

data ReadOnlyMemory<byte>

The encoded file.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read each image, or null for Default.

Returns

RasterList

The images, in the file's order. The caller must dispose the list.

Examples

// Every page at its own size and pixel type. The list owns the rasters.
using RasterList pages = Raster.LoadAll("scan.tif");
foreach (Raster page in pages)
{
    Console.WriteLine($"{page.Width} × {page.Height}");
}

// Keep one page after the list is gone.
using Raster first = pages.Detach(0);

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

An image or the images together break a safety limit.

LoadAll(ReadOnlyMemory<byte>, FormatInfo, EgamiContext?, ReaderOptions?)

Loads every image of a file of a known format in memory. See LoadAll(Stream, EgamiContext?, ReaderOptions?).

public static RasterList LoadAll(ReadOnlyMemory<byte> data, FormatInfo format, EgamiContext? context = null, ReaderOptions? options = null)

Parameters

data ReadOnlyMemory<byte>

The encoded file.

format FormatInfo

The format to read with. It need not be registered in the context.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read each image, or null for Default.

Returns

RasterList

The images, in the file's order. The caller must dispose the list.

Examples

// Data without a signature of its own (a TGA here; a JBIG2 stream from a PDF) loads with its format named,
// which skips detection. Probe, LoadAll and RasterDecoder.Open take the format the same way.
using Raster image = Raster.Load(data, TgaFormat.Info);
RasterInfo info = Raster.Probe(data, TgaFormat.Info);

Exceptions

UnsupportedFormatException

format has no reader.

CorruptDataException

The data breaks the format's rules, including data of another format.

LimitExceededException

An image or the images together break a safety limit.

ArgumentNullException

format is null.

LoadAll(string, EgamiContext?, ReaderOptions?)

Loads every image of a file. See LoadAll(Stream, EgamiContext?, ReaderOptions?).

public static RasterList LoadAll(string path, EgamiContext? context = null, ReaderOptions? options = null)

Parameters

path string

The file path.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read each image, or null for Default.

Returns

RasterList

The images, in the file's order. The caller must dispose the list.

Examples

// Every page at its own size and pixel type. The list owns the rasters.
using RasterList pages = Raster.LoadAll("scan.tif");
foreach (Raster page in pages)
{
    Console.WriteLine($"{page.Width} × {page.Height}");
}

// Keep one page after the list is gone.
using Raster first = pages.Detach(0);

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

An image or the images together break a safety limit.

ArgumentNullException

path is null.

FileNotFoundException

The file does not exist.

IOException

The file cannot be read.

LoadAllAsync(Stream, EgamiContext?, ReaderOptions?, CancellationToken)

Reads the file asynchronously, then loads every image. See LoadAll(Stream, EgamiContext?, ReaderOptions?); the bytes held count against MaxTotalBytes.

public static Task<RasterList> LoadAllAsync(Stream stream, EgamiContext? context = null, ReaderOptions? options = null, CancellationToken cancellationToken = default)

Parameters

stream Stream

The encoded file.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read each image, or null for Default.

cancellationToken CancellationToken

Cancels reading and, between images, decoding.

Returns

Task<RasterList>

The images, in the file's order. The caller must dispose the list.

Examples

// Every page at its own size and pixel type. The list owns the rasters.
using RasterList pages = Raster.LoadAll("scan.tif");
foreach (Raster page in pages)
{
    Console.WriteLine($"{page.Width} × {page.Height}");
}

// Keep one page after the list is gone.
using Raster first = pages.Detach(0);

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

An image or the images together break a safety limit.

ArgumentNullException

stream is null.

OperationCanceledException

cancellationToken was canceled.

LoadAllAsync(string, EgamiContext?, ReaderOptions?, CancellationToken)

Reads an image file asynchronously, then loads every image. See LoadAllAsync(Stream, EgamiContext?, ReaderOptions?, CancellationToken).

public static Task<RasterList> LoadAllAsync(string path, EgamiContext? context = null, ReaderOptions? options = null, CancellationToken cancellationToken = default)

Parameters

path string

The file path.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read each image, or null for Default.

cancellationToken CancellationToken

Cancels reading and decoding.

Returns

Task<RasterList>

The images, in the file's order. The caller must dispose the list.

Examples

// Every page at its own size and pixel type. The list owns the rasters.
using RasterList pages = Raster.LoadAll("scan.tif");
foreach (Raster page in pages)
{
    Console.WriteLine($"{page.Width} × {page.Height}");
}

// Keep one page after the list is gone.
using Raster first = pages.Detach(0);

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

An image or the images together break a safety limit.

ArgumentNullException

path is null.

FileNotFoundException

The file does not exist.

IOException

The file cannot be read.

OperationCanceledException

cancellationToken was canceled.

LoadAllAsync<TPixel>(Stream, EgamiContext?, ReaderOptions?, CancellationToken)

Reads the file asynchronously, then loads every image as TPixel. See LoadAllAsync(Stream, EgamiContext?, ReaderOptions?, CancellationToken).

public static Task<RasterList> LoadAllAsync<TPixel>(Stream stream, EgamiContext? context = null, ReaderOptions? options = null, CancellationToken cancellationToken = default) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

stream Stream

The encoded file.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read each image, or null for Default.

cancellationToken CancellationToken

Cancels reading and decoding.

Returns

Task<RasterList>

The images, in the file's order. The caller must dispose the list.

Type Parameters

TPixel

The pixel type to produce.

Examples

// Every page at its own size and pixel type. The list owns the rasters.
using RasterList pages = Raster.LoadAll("scan.tif");
foreach (Raster page in pages)
{
    Console.WriteLine($"{page.Width} × {page.Height}");
}

// Keep one page after the list is gone.
using Raster first = pages.Detach(0);

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

An image or the images together break a safety limit.

ArgumentNullException

stream is null.

OperationCanceledException

cancellationToken was canceled.

LoadAllAsync<TPixel>(string, EgamiContext?, ReaderOptions?, CancellationToken)

Reads an image file asynchronously, then loads every image as TPixel. See LoadAllAsync(Stream, EgamiContext?, ReaderOptions?, CancellationToken).

public static Task<RasterList> LoadAllAsync<TPixel>(string path, EgamiContext? context = null, ReaderOptions? options = null, CancellationToken cancellationToken = default) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

path string

The file path.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read each image, or null for Default.

cancellationToken CancellationToken

Cancels reading and decoding.

Returns

Task<RasterList>

The images, in the file's order. The caller must dispose the list.

Type Parameters

TPixel

The pixel type to produce.

Examples

// Every page at its own size and pixel type. The list owns the rasters.
using RasterList pages = Raster.LoadAll("scan.tif");
foreach (Raster page in pages)
{
    Console.WriteLine($"{page.Width} × {page.Height}");
}

// Keep one page after the list is gone.
using Raster first = pages.Detach(0);

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

An image or the images together break a safety limit.

ArgumentNullException

path is null.

FileNotFoundException

The file does not exist.

IOException

The file cannot be read.

OperationCanceledException

cancellationToken was canceled.

LoadAll<TPixel>(Stream, EgamiContext?, ReaderOptions?)

Loads every image of a file as TPixel. See LoadAll(Stream, EgamiContext?, ReaderOptions?).

public static RasterList LoadAll<TPixel>(Stream stream, EgamiContext? context = null, ReaderOptions? options = null) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

stream Stream

The encoded file.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read each image, or null for Default.

Returns

RasterList

The images, in the file's order. The caller must dispose the list.

Type Parameters

TPixel

The pixel type to produce; each image in the list is a Raster<TPixel>.

Examples

// Every page at its own size and pixel type. The list owns the rasters.
using RasterList pages = Raster.LoadAll("scan.tif");
foreach (Raster page in pages)
{
    Console.WriteLine($"{page.Width} × {page.Height}");
}

// Keep one page after the list is gone.
using Raster first = pages.Detach(0);

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

An image or the images together break a safety limit.

ArgumentNullException

stream is null.

LoadAll<TPixel>(Stream, FormatInfo, EgamiContext?, ReaderOptions?)

Loads every image of a file of a known format as TPixel. See LoadAll(Stream, EgamiContext?, ReaderOptions?).

public static RasterList LoadAll<TPixel>(Stream stream, FormatInfo format, EgamiContext? context = null, ReaderOptions? options = null) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

stream Stream

The encoded file.

format FormatInfo

The format to read with. It need not be registered in the context.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read each image, or null for Default.

Returns

RasterList

The images, in the file's order. The caller must dispose the list.

Type Parameters

TPixel

The pixel type to produce; each image in the list is a Raster<TPixel>.

Examples

// Data without a signature of its own (a TGA here; a JBIG2 stream from a PDF) loads with its format named,
// which skips detection. Probe, LoadAll and RasterDecoder.Open take the format the same way.
using Raster image = Raster.Load(data, TgaFormat.Info);
RasterInfo info = Raster.Probe(data, TgaFormat.Info);

Exceptions

UnsupportedFormatException

format has no reader.

CorruptDataException

The data breaks the format's rules, including data of another format.

LimitExceededException

An image or the images together break a safety limit.

ArgumentNullException

stream or format is null.

LoadAll<TPixel>(ReadOnlyMemory<byte>, EgamiContext?, ReaderOptions?)

Loads every image of a file in memory as TPixel. See LoadAll(Stream, EgamiContext?, ReaderOptions?).

public static RasterList LoadAll<TPixel>(ReadOnlyMemory<byte> data, EgamiContext? context = null, ReaderOptions? options = null) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

data ReadOnlyMemory<byte>

The encoded file.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read each image, or null for Default.

Returns

RasterList

The images, in the file's order. The caller must dispose the list.

Type Parameters

TPixel

The pixel type to produce.

Examples

// Every page at its own size and pixel type. The list owns the rasters.
using RasterList pages = Raster.LoadAll("scan.tif");
foreach (Raster page in pages)
{
    Console.WriteLine($"{page.Width} × {page.Height}");
}

// Keep one page after the list is gone.
using Raster first = pages.Detach(0);

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

An image or the images together break a safety limit.

LoadAll<TPixel>(ReadOnlyMemory<byte>, FormatInfo, EgamiContext?, ReaderOptions?)

Loads every image of a file of a known format in memory as TPixel. See LoadAll(Stream, EgamiContext?, ReaderOptions?).

public static RasterList LoadAll<TPixel>(ReadOnlyMemory<byte> data, FormatInfo format, EgamiContext? context = null, ReaderOptions? options = null) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

data ReadOnlyMemory<byte>

The encoded file.

format FormatInfo

The format to read with. It need not be registered in the context.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read each image, or null for Default.

Returns

RasterList

The images, in the file's order. The caller must dispose the list.

Type Parameters

TPixel

The pixel type to produce; each image in the list is a Raster<TPixel>.

Examples

// Data without a signature of its own (a TGA here; a JBIG2 stream from a PDF) loads with its format named,
// which skips detection. Probe, LoadAll and RasterDecoder.Open take the format the same way.
using Raster image = Raster.Load(data, TgaFormat.Info);
RasterInfo info = Raster.Probe(data, TgaFormat.Info);

Exceptions

UnsupportedFormatException

format has no reader.

CorruptDataException

The data breaks the format's rules, including data of another format.

LimitExceededException

An image or the images together break a safety limit.

ArgumentNullException

format is null.

LoadAll<TPixel>(string, EgamiContext?, ReaderOptions?)

Loads every image of a file as TPixel. See LoadAll(Stream, EgamiContext?, ReaderOptions?).

public static RasterList LoadAll<TPixel>(string path, EgamiContext? context = null, ReaderOptions? options = null) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

path string

The file path.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read each image, or null for Default.

Returns

RasterList

The images, in the file's order. The caller must dispose the list.

Type Parameters

TPixel

The pixel type to produce.

Examples

// Every page at its own size and pixel type. The list owns the rasters.
using RasterList pages = Raster.LoadAll("scan.tif");
foreach (Raster page in pages)
{
    Console.WriteLine($"{page.Width} × {page.Height}");
}

// Keep one page after the list is gone.
using Raster first = pages.Detach(0);

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

An image or the images together break a safety limit.

ArgumentNullException

path is null.

FileNotFoundException

The file does not exist.

IOException

The file cannot be read.

LoadAsync(Stream, EgamiContext?, ReaderOptions?, CancellationToken)

Reads the encoded image asynchronously. A stream that cannot seek, such as an upload, is decoded 256 KB at a time as it arrives, so decoding overlaps the wait and only the bytes since the decode's last step are held, not the whole file. A seekable stream, and formats from plugins, files decoded into a buffer first (such as bottom-up BMP) and progressive JPEG, are read whole and then decoded; the bytes held count against MaxTotalBytes. Decoding itself is synchronous, since it is CPU-bound.

public static Task<Raster> LoadAsync(Stream stream, EgamiContext? context = null, ReaderOptions? options = null, CancellationToken cancellationToken = default)

Parameters

stream Stream

The encoded image.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read, or null for Default.

cancellationToken CancellationToken

Cancels reading and, between rows, decoding.

Returns

Task<Raster>

The raster. The caller must dispose it.

Examples

// Every Load, Probe and Save has an async twin. Async reads the stream into a pooled buffer first,
// then decodes (decoding is CPU work, so it is synchronous either way).
await using FileStream stream = File.OpenRead("duck.png");
using Raster image = await Raster.LoadAsync(stream, cancellationToken: cancellationToken);
await image.SaveAsync("duck-copy.png", cancellationToken: cancellationToken);

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

The image breaks a safety limit.

ArgumentNullException

stream is null.

OperationCanceledException

cancellationToken was canceled.

LoadAsync(string, EgamiContext?, ReaderOptions?, CancellationToken)

public static Task<Raster> LoadAsync(string path, EgamiContext? context = null, ReaderOptions? options = null, CancellationToken cancellationToken = default)

Parameters

path string

The file path.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read, or null for Default.

cancellationToken CancellationToken

Cancels reading and decoding.

Returns

Task<Raster>

The raster. The caller must dispose it.

Examples

// Every Load, Probe and Save has an async twin. Async reads the stream into a pooled buffer first,
// then decodes (decoding is CPU work, so it is synchronous either way).
await using FileStream stream = File.OpenRead("duck.png");
using Raster image = await Raster.LoadAsync(stream, cancellationToken: cancellationToken);
await image.SaveAsync("duck-copy.png", cancellationToken: cancellationToken);

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

The image breaks a safety limit.

ArgumentNullException

path is null.

FileNotFoundException

The file does not exist.

IOException

The file cannot be read.

OperationCanceledException

cancellationToken was canceled.

LoadAsync<TPixel>(Stream, EgamiContext?, ReaderOptions?, CancellationToken)

Reads the encoded image asynchronously, decoding it as TPixel as it arrives. See LoadAsync(Stream, EgamiContext?, ReaderOptions?, CancellationToken).

public static Task<Raster<TPixel>> LoadAsync<TPixel>(Stream stream, EgamiContext? context = null, ReaderOptions? options = null, CancellationToken cancellationToken = default) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

stream Stream

The encoded image.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read, or null for Default.

cancellationToken CancellationToken

Cancels reading and decoding.

Returns

Task<Raster<TPixel>>

The raster. The caller must dispose it.

Type Parameters

TPixel

The pixel type to produce.

Examples

// Every Load, Probe and Save has an async twin. Async reads the stream into a pooled buffer first,
// then decodes (decoding is CPU work, so it is synchronous either way).
await using FileStream stream = File.OpenRead("duck.png");
using Raster image = await Raster.LoadAsync(stream, cancellationToken: cancellationToken);
await image.SaveAsync("duck-copy.png", cancellationToken: cancellationToken);

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

The image breaks a safety limit.

ArgumentNullException

stream is null.

OperationCanceledException

cancellationToken was canceled.

LoadAsync<TPixel>(string, EgamiContext?, ReaderOptions?, CancellationToken)

Loads an image file asynchronously as TPixel.

public static Task<Raster<TPixel>> LoadAsync<TPixel>(string path, EgamiContext? context = null, ReaderOptions? options = null, CancellationToken cancellationToken = default) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

path string

The file path.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read, or null for Default.

cancellationToken CancellationToken

Cancels reading and decoding.

Returns

Task<Raster<TPixel>>

The raster. The caller must dispose it.

Type Parameters

TPixel

The pixel type to produce.

Examples

// Every Load, Probe and Save has an async twin. Async reads the stream into a pooled buffer first,
// then decodes (decoding is CPU work, so it is synchronous either way).
await using FileStream stream = File.OpenRead("duck.png");
using Raster image = await Raster.LoadAsync(stream, cancellationToken: cancellationToken);
await image.SaveAsync("duck-copy.png", cancellationToken: cancellationToken);

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

The image breaks a safety limit.

ArgumentNullException

path is null.

FileNotFoundException

The file does not exist.

IOException

The file cannot be read.

OperationCanceledException

cancellationToken was canceled.

LoadInto<TPixel>(Stream, Raster<TPixel>, EgamiContext?, ReaderOptions?)

Decodes the first frame Frames selects into a raster the caller already has, so pooled images and video frames reuse their memory. target's metadata is replaced with the file's; only working buffers are allocated.

public static void LoadInto<TPixel>(Stream stream, Raster<TPixel> target, EgamiContext? context = null, ReaderOptions? options = null) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

stream Stream

The encoded image. It is read from its current position and left open.

target Raster<TPixel>

Where to decode: the size the image decodes to, after Region and MinimumSize. Only its first frame is written.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read, or null for Default.

Type Parameters

TPixel

The target's pixel type.

Examples

// Decode into a raster you already have: video frames and pooled images reuse their memory.
using Raster<Rgb8> reused = Raster.Create<Rgb8>(480, 640);
Raster.LoadInto("egret.png", reused);

Exceptions

ArgumentException

target is not the size the image decodes to; the message names both sizes.

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

The image breaks a safety limit.

ArgumentNullException

stream or target is null.

LoadInto<TPixel>(ReadOnlyMemory<byte>, Raster<TPixel>, EgamiContext?, ReaderOptions?)

Decodes an image from bytes in memory into a raster the caller already has. See LoadInto<TPixel>(Stream, Raster<TPixel>, EgamiContext?, ReaderOptions?).

public static void LoadInto<TPixel>(ReadOnlyMemory<byte> data, Raster<TPixel> target, EgamiContext? context = null, ReaderOptions? options = null) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

data ReadOnlyMemory<byte>

The encoded image.

target Raster<TPixel>

Where to decode: the size the image decodes to. Only its first frame is written.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read, or null for Default.

Type Parameters

TPixel

The target's pixel type.

Examples

// Decode into a raster you already have: video frames and pooled images reuse their memory.
using Raster<Rgb8> reused = Raster.Create<Rgb8>(480, 640);
Raster.LoadInto("egret.png", reused);

Exceptions

ArgumentException

target is not the size the image decodes to; the message names both sizes.

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

The image breaks a safety limit.

ArgumentNullException

target is null.

LoadInto<TPixel>(string, Raster<TPixel>, EgamiContext?, ReaderOptions?)

Decodes an image file into a raster the caller already has. See LoadInto<TPixel>(Stream, Raster<TPixel>, EgamiContext?, ReaderOptions?).

public static void LoadInto<TPixel>(string path, Raster<TPixel> target, EgamiContext? context = null, ReaderOptions? options = null) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

path string

The file path.

target Raster<TPixel>

Where to decode: the size the image decodes to. Only its first frame is written.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read, or null for Default.

Type Parameters

TPixel

The target's pixel type.

Examples

// Decode into a raster you already have: video frames and pooled images reuse their memory.
using Raster<Rgb8> reused = Raster.Create<Rgb8>(480, 640);
Raster.LoadInto("egret.png", reused);

Exceptions

ArgumentException

target is not the size the image decodes to; the message names both sizes.

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

The image breaks a safety limit.

ArgumentNullException

path or target is null.

FileNotFoundException

The file does not exist.

IOException

The file cannot be read.

Load<TPixel>(Stream, EgamiContext?, ReaderOptions?)

Detects the format and decodes the image straight into TPixel, converting row by row while decoding. See Load(Stream, EgamiContext?, ReaderOptions?).

public static Raster<TPixel> Load<TPixel>(Stream stream, EgamiContext? context = null, ReaderOptions? options = null) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

stream Stream

The encoded image.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read, or null for Default.

Returns

Raster<TPixel>

The raster. The caller must dispose it.

Type Parameters

TPixel

The pixel type to produce.

Examples

// Decode straight into the type you want to work in.
using Raster<Rgba8> rgba = Raster.Load<Rgba8>("duck.png");

// Pixels are a row at a time: each row is a Span<Rgba8>.
for (int y = 0; y < rgba.Height; y++)
{
    Span<Rgba8> row = rgba.Row(y);
    for (int x = 0; x < row.Length; x++)
    {
        row[x].A = 128;
    }
}

// Convert a whole raster; the result is a new raster you dispose too.
using Raster<Gray8> gray = rgba.As<Gray8>();
gray.Save("duck-gray.png");

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

The image breaks a safety limit.

ArgumentNullException

stream is null.

Load<TPixel>(Stream, FormatInfo, EgamiContext?, ReaderOptions?)

Decodes an image of a known format as TPixel. See Load(Stream, FormatInfo, EgamiContext?, ReaderOptions?).

public static Raster<TPixel> Load<TPixel>(Stream stream, FormatInfo format, EgamiContext? context = null, ReaderOptions? options = null) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

stream Stream

The encoded image.

format FormatInfo

The format to read with. It need not be registered in the context.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read, or null for Default.

Returns

Raster<TPixel>

The raster. The caller must dispose it.

Type Parameters

TPixel

The pixel type to produce.

Examples

// Data without a signature of its own (a TGA here; a JBIG2 stream from a PDF) loads with its format named,
// which skips detection. Probe, LoadAll and RasterDecoder.Open take the format the same way.
using Raster image = Raster.Load(data, TgaFormat.Info);
RasterInfo info = Raster.Probe(data, TgaFormat.Info);

Exceptions

UnsupportedFormatException

format has no reader.

CorruptDataException

The data breaks the format's rules, including data of another format.

LimitExceededException

The image breaks a safety limit.

ArgumentNullException

stream or format is null.

Load<TPixel>(ReadOnlyMemory<byte>, EgamiContext?, ReaderOptions?)

Loads an image from bytes in memory as TPixel.

public static Raster<TPixel> Load<TPixel>(ReadOnlyMemory<byte> data, EgamiContext? context = null, ReaderOptions? options = null) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

data ReadOnlyMemory<byte>

The encoded image.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read, or null for Default.

Returns

Raster<TPixel>

The raster. The caller must dispose it.

Type Parameters

TPixel

The pixel type to produce.

Examples

// Decode straight into the type you want to work in.
using Raster<Rgba8> rgba = Raster.Load<Rgba8>("duck.png");

// Pixels are a row at a time: each row is a Span<Rgba8>.
for (int y = 0; y < rgba.Height; y++)
{
    Span<Rgba8> row = rgba.Row(y);
    for (int x = 0; x < row.Length; x++)
    {
        row[x].A = 128;
    }
}

// Convert a whole raster; the result is a new raster you dispose too.
using Raster<Gray8> gray = rgba.As<Gray8>();
gray.Save("duck-gray.png");

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

The image breaks a safety limit.

Load<TPixel>(ReadOnlyMemory<byte>, FormatInfo, EgamiContext?, ReaderOptions?)

Decodes an image of a known format from bytes in memory as TPixel. See Load(Stream, FormatInfo, EgamiContext?, ReaderOptions?).

public static Raster<TPixel> Load<TPixel>(ReadOnlyMemory<byte> data, FormatInfo format, EgamiContext? context = null, ReaderOptions? options = null) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

data ReadOnlyMemory<byte>

The encoded image.

format FormatInfo

The format to read with. It need not be registered in the context.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read, or null for Default.

Returns

Raster<TPixel>

The raster. The caller must dispose it.

Type Parameters

TPixel

The pixel type to produce.

Examples

// Data without a signature of its own (a TGA here; a JBIG2 stream from a PDF) loads with its format named,
// which skips detection. Probe, LoadAll and RasterDecoder.Open take the format the same way.
using Raster image = Raster.Load(data, TgaFormat.Info);
RasterInfo info = Raster.Probe(data, TgaFormat.Info);

Exceptions

UnsupportedFormatException

format has no reader.

CorruptDataException

The data breaks the format's rules, including data of another format.

LimitExceededException

The image breaks a safety limit.

ArgumentNullException

format is null.

Load<TPixel>(string, EgamiContext?, ReaderOptions?)

Loads an image file as TPixel.

public static Raster<TPixel> Load<TPixel>(string path, EgamiContext? context = null, ReaderOptions? options = null) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

path string

The file path.

context EgamiContext

The context, or null for Default.

options ReaderOptions

How to read, or null for Default.

Returns

Raster<TPixel>

The raster. The caller must dispose it.

Type Parameters

TPixel

The pixel type to produce.

Examples

// Decode straight into the type you want to work in.
using Raster<Rgba8> rgba = Raster.Load<Rgba8>("duck.png");

// Pixels are a row at a time: each row is a Span<Rgba8>.
for (int y = 0; y < rgba.Height; y++)
{
    Span<Rgba8> row = rgba.Row(y);
    for (int x = 0; x < row.Length; x++)
    {
        row[x].A = 128;
    }
}

// Convert a whole raster; the result is a new raster you dispose too.
using Raster<Gray8> gray = rgba.As<Gray8>();
gray.Save("duck-gray.png");

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The data breaks the format's rules.

LimitExceededException

The image breaks a safety limit.

ArgumentNullException

path is null.

FileNotFoundException

The file does not exist.

IOException

The file cannot be read.

MeasureAutoGamma(bool)

Returns the filter AutoGamma(bool, bool) would apply, measured on every frame.

public ColorFilter MeasureAutoGamma(bool linked = true)

Parameters

linked bool

Whether the channels share one gamma (the default) or each gets its own.

Returns

ColorFilter

The filter.

Examples

// Measure once on a reference shot, then apply the same correction to the whole shoot.
ColorFilter fix = reference.MeasureAutoLevel().Then(reference.MeasureWhiteBalance());
foreach (Raster<Rgba8> shot in shoot)
{
    shot.Apply(o => o.ApplyFilter(fix), Ct);
}

// The other measured steps have their Measure helpers too.
ColorFilter stretch = reference.MeasureContrastStretch(0.02f, 0.01f);
ColorFilter midtones = reference.MeasureAutoGamma();
ColorFilter spread = reference.MeasureEqualize();

Exceptions

ObjectDisposedException

The raster has been disposed.

MeasureAutoLevel(bool)

Returns the filter AutoLevel(bool, bool) would apply, measured on every frame: apply it to other images to give them the same correction.

public ColorFilter MeasureAutoLevel(bool linked = true)

Parameters

linked bool

Whether the channels share one black and one white point (the default) or each gets its own.

Returns

ColorFilter

The filter, a level per channel.

Examples

// Measure once on a reference shot, then apply the same correction to the whole shoot.
ColorFilter fix = reference.MeasureAutoLevel().Then(reference.MeasureWhiteBalance());
foreach (Raster<Rgba8> shot in shoot)
{
    shot.Apply(o => o.ApplyFilter(fix), Ct);
}

// The other measured steps have their Measure helpers too.
ColorFilter stretch = reference.MeasureContrastStretch(0.02f, 0.01f);
ColorFilter midtones = reference.MeasureAutoGamma();
ColorFilter spread = reference.MeasureEqualize();

Exceptions

ObjectDisposedException

The raster has been disposed.

MeasureContrastStretch(float, float, bool)

Returns the filter ContrastStretch(float, float, bool, bool) would apply, measured on every frame.

public ColorFilter MeasureContrastStretch(float black, float white, bool linked = true)

Parameters

black float

The fraction of pixels that becomes black, from 0 to 1.

white float

The fraction that becomes white, from 0 to 1; with black less than 1.

linked bool

Whether the channels share one pair of points (the default) or each gets its own.

Returns

ColorFilter

The filter.

Examples

// Measure once on a reference shot, then apply the same correction to the whole shoot.
ColorFilter fix = reference.MeasureAutoLevel().Then(reference.MeasureWhiteBalance());
foreach (Raster<Rgba8> shot in shoot)
{
    shot.Apply(o => o.ApplyFilter(fix), Ct);
}

// The other measured steps have their Measure helpers too.
ColorFilter stretch = reference.MeasureContrastStretch(0.02f, 0.01f);
ColorFilter midtones = reference.MeasureAutoGamma();
ColorFilter spread = reference.MeasureEqualize();

Exceptions

ArgumentOutOfRangeException

A fraction is outside 0..1, or the two add up to 1 or more.

ObjectDisposedException

The raster has been disposed.

MeasureEqualize(EqualizeMode)

Returns the filter Equalize(EqualizeMode, bool) would apply, measured on every frame.

public ColorFilter MeasureEqualize(EqualizeMode mode = EqualizeMode.Luminance)

Parameters

mode EqualizeMode

What is equalized. Defaults to Luminance.

Returns

ColorFilter

The filter.

Examples

// Measure once on a reference shot, then apply the same correction to the whole shoot.
ColorFilter fix = reference.MeasureAutoLevel().Then(reference.MeasureWhiteBalance());
foreach (Raster<Rgba8> shot in shoot)
{
    shot.Apply(o => o.ApplyFilter(fix), Ct);
}

// The other measured steps have their Measure helpers too.
ColorFilter stretch = reference.MeasureContrastStretch(0.02f, 0.01f);
ColorFilter midtones = reference.MeasureAutoGamma();
ColorFilter spread = reference.MeasureEqualize();

Exceptions

ArgumentOutOfRangeException

mode is not defined.

ObjectDisposedException

The raster has been disposed.

MeasureWhiteBalance(WhiteBalanceMethod)

Returns the filter AutoWhiteBalance(WhiteBalanceMethod, bool) would apply, measured on every frame: measure a reference shot once and apply the result to the whole shoot.

public ColorFilter MeasureWhiteBalance(WhiteBalanceMethod method = WhiteBalanceMethod.GrayWorld)

Parameters

method WhiteBalanceMethod

How the cast is found. Defaults to GrayWorld.

Returns

ColorFilter

The filter.

Examples

// Measure once on a reference shot, then apply the same correction to the whole shoot.
ColorFilter fix = reference.MeasureAutoLevel().Then(reference.MeasureWhiteBalance());
foreach (Raster<Rgba8> shot in shoot)
{
    shot.Apply(o => o.ApplyFilter(fix), Ct);
}

// The other measured steps have their Measure helpers too.
ColorFilter stretch = reference.MeasureContrastStretch(0.02f, 0.01f);
ColorFilter midtones = reference.MeasureAutoGamma();
ColorFilter spread = reference.MeasureEqualize();

Exceptions

ArgumentOutOfRangeException

method is not defined.

ObjectDisposedException

The raster has been disposed.

Probe(Stream, EgamiContext?, ReaderOptions?)

Reads only the header: format, size, natural pixel layout, frame count when cheap, metadata presence and the estimated memory a full load would allocate. No pixel memory is allocated.

public static RasterInfo Probe(Stream stream, EgamiContext? context = null, ReaderOptions? options = null)

Parameters

stream Stream

The encoded image. A seekable stream ends just past the bytes read.

context EgamiContext

The context, or null for Default.

options ReaderOptions

Reader options, or null for the defaults. MinimumSize lowers the estimate for formats that can decode at a smaller scale, and Recovery applies to the header.

Returns

RasterInfo

What the header says.

Examples

RasterInfo info = Raster.Probe("sideways.jpg");
bool sideways = info.Orientation is >= Egami.Metadata.ImageOrientation.Transpose;
(int width, int height) = sideways ? (info.Height, info.Width) : (info.Width, info.Height);
Console.WriteLine($"{info.Format.Name}, shown as {width} × {height}, about {info.EstimatedBytes:N0} bytes to load");

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The header breaks the format's rules.

LimitExceededException

The header breaks a safety limit, such as the metadata size.

ArgumentNullException

stream is null.

Probe(Stream, FormatInfo, EgamiContext?, ReaderOptions?)

Reads only the header of an image of a known format. See Probe(Stream, EgamiContext?, ReaderOptions?).

public static RasterInfo Probe(Stream stream, FormatInfo format, EgamiContext? context = null, ReaderOptions? options = null)

Parameters

stream Stream

The encoded image. A seekable stream ends just past the bytes read.

format FormatInfo

The format to read with. It need not be registered in the context.

context EgamiContext

The context, or null for Default.

options ReaderOptions

Reader options, or null for the defaults.

Returns

RasterInfo

What the header says.

Examples

// Data without a signature of its own (a TGA here; a JBIG2 stream from a PDF) loads with its format named,
// which skips detection. Probe, LoadAll and RasterDecoder.Open take the format the same way.
using Raster image = Raster.Load(data, TgaFormat.Info);
RasterInfo info = Raster.Probe(data, TgaFormat.Info);

Exceptions

UnsupportedFormatException

format has no reader.

CorruptDataException

The header breaks the format's rules, including data of another format.

LimitExceededException

The header breaks a safety limit.

ArgumentNullException

stream or format is null.

Probe(ReadOnlyMemory<byte>, EgamiContext?, ReaderOptions?)

Reads only the header of an image in memory. See Probe(Stream, EgamiContext?, ReaderOptions?).

public static RasterInfo Probe(ReadOnlyMemory<byte> data, EgamiContext? context = null, ReaderOptions? options = null)

Parameters

data ReadOnlyMemory<byte>

The encoded image.

context EgamiContext

The context, or null for Default.

options ReaderOptions

Reader options, or null for the defaults. MinimumSize lowers the estimate for formats that can decode at a smaller scale, and Recovery applies to the header.

Returns

RasterInfo

What the header says.

Examples

RasterInfo info = Raster.Probe("sideways.jpg");
bool sideways = info.Orientation is >= Egami.Metadata.ImageOrientation.Transpose;
(int width, int height) = sideways ? (info.Height, info.Width) : (info.Width, info.Height);
Console.WriteLine($"{info.Format.Name}, shown as {width} × {height}, about {info.EstimatedBytes:N0} bytes to load");

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The header breaks the format's rules.

LimitExceededException

The header breaks a safety limit, such as the metadata size.

Probe(ReadOnlyMemory<byte>, FormatInfo, EgamiContext?, ReaderOptions?)

Reads only the header of an image of a known format in memory. See Probe(Stream, EgamiContext?, ReaderOptions?).

public static RasterInfo Probe(ReadOnlyMemory<byte> data, FormatInfo format, EgamiContext? context = null, ReaderOptions? options = null)

Parameters

data ReadOnlyMemory<byte>

The encoded image.

format FormatInfo

The format to read with. It need not be registered in the context.

context EgamiContext

The context, or null for Default.

options ReaderOptions

Reader options, or null for the defaults.

Returns

RasterInfo

What the header says.

Examples

// Data without a signature of its own (a TGA here; a JBIG2 stream from a PDF) loads with its format named,
// which skips detection. Probe, LoadAll and RasterDecoder.Open take the format the same way.
using Raster image = Raster.Load(data, TgaFormat.Info);
RasterInfo info = Raster.Probe(data, TgaFormat.Info);

Exceptions

UnsupportedFormatException

format has no reader.

CorruptDataException

The header breaks the format's rules, including data of another format.

LimitExceededException

The header breaks a safety limit.

ArgumentNullException

format is null.

Probe(string, EgamiContext?, ReaderOptions?)

Reads only the header of an image file. See Probe(Stream, EgamiContext?, ReaderOptions?).

public static RasterInfo Probe(string path, EgamiContext? context = null, ReaderOptions? options = null)

Parameters

path string

The file path.

context EgamiContext

The context, or null for Default.

options ReaderOptions

Reader options, or null for the defaults. MinimumSize lowers the estimate for formats that can decode at a smaller scale, and Recovery applies to the header.

Returns

RasterInfo

What the header says.

Examples

RasterInfo info = Raster.Probe("sideways.jpg");
bool sideways = info.Orientation is >= Egami.Metadata.ImageOrientation.Transpose;
(int width, int height) = sideways ? (info.Height, info.Width) : (info.Width, info.Height);
Console.WriteLine($"{info.Format.Name}, shown as {width} × {height}, about {info.EstimatedBytes:N0} bytes to load");

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The header breaks the format's rules.

LimitExceededException

The header breaks a safety limit, such as the metadata size.

ArgumentNullException

path is null.

FileNotFoundException

The file does not exist.

IOException

The file cannot be read.

ProbeAsync(Stream, EgamiContext?, ReaderOptions?, CancellationToken)

Reads the header asynchronously, reading only as much of the stream as the header needs (at least 64 KB, or all of it if shorter). See Probe(Stream, EgamiContext?, ReaderOptions?).

public static Task<RasterInfo> ProbeAsync(Stream stream, EgamiContext? context = null, ReaderOptions? options = null, CancellationToken cancellationToken = default)

Parameters

stream Stream

The encoded image.

context EgamiContext

The context, or null for Default.

options ReaderOptions

Reader options, or null for the defaults. MinimumSize lowers the estimate for formats that can decode at a smaller scale, and Recovery applies to the header.

cancellationToken CancellationToken

Cancels reading.

Returns

Task<RasterInfo>

What the header says.

Examples

// The header only: size, format, frames and metadata, without decoding the pixels.
RasterInfo info = await Raster.ProbeAsync("pan.gif", cancellationToken: cancellationToken);
Console.WriteLine($"{info.Format.Name} {info.Width} × {info.Height}, {info.FrameCount} frames");

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The header breaks the format's rules.

LimitExceededException

The header breaks a safety limit, such as the metadata size.

ArgumentNullException

stream is null.

OperationCanceledException

cancellationToken was canceled.

ProbeAsync(string, EgamiContext?, ReaderOptions?, CancellationToken)

Reads the header of an image file asynchronously. See Probe(Stream, EgamiContext?, ReaderOptions?).

public static Task<RasterInfo> ProbeAsync(string path, EgamiContext? context = null, ReaderOptions? options = null, CancellationToken cancellationToken = default)

Parameters

path string

The file path.

context EgamiContext

The context, or null for Default.

options ReaderOptions

Reader options, or null for the defaults. MinimumSize lowers the estimate for formats that can decode at a smaller scale, and Recovery applies to the header.

cancellationToken CancellationToken

Cancels reading.

Returns

Task<RasterInfo>

What the header says.

Examples

// The header only: size, format, frames and metadata, without decoding the pixels.
RasterInfo info = await Raster.ProbeAsync("pan.gif", cancellationToken: cancellationToken);
Console.WriteLine($"{info.Format.Name} {info.Width} × {info.Height}, {info.FrameCount} frames");

Exceptions

UnsupportedFormatException

No registered format matches the data.

CorruptDataException

The header breaks the format's rules.

LimitExceededException

The header breaks a safety limit, such as the metadata size.

ArgumentNullException

path is null.

FileNotFoundException

The file does not exist.

IOException

The file cannot be read.

OperationCanceledException

cancellationToken was canceled.

Save(Stream, FormatInfo, WriterOptions?)

Encodes the raster in format. The raster is not changed.

public void Save(Stream stream, FormatInfo format, WriterOptions? options = null)

Parameters

stream Stream

Where to write, from its current position. It is left open.

format FormatInfo

The format.

options WriterOptions

The format's options, or null for its defaults.

Examples

using FileStream output = File.Create("duck-small.png");
image.Save(output, PngFormat.Info, new PngWriterOptions
{
    Reduce = true,          // the smallest exact form: no alpha if all opaque, gray or a palette when nothing is lost
    CompressionLevel = 9,   // 0 (fastest) to 9 (smallest); 5 by default
});

Exceptions

UnsupportedFormatException

The format has no writer.

ObjectDisposedException

The raster has been disposed.

ArgumentNullException

stream is null.

Save(Stream, FormatInfo, WriterOptions?, IProgress<SaveProgress>?, CancellationToken)

Encodes the raster in format as Save(Stream, FormatInfo, WriterOptions?) does, reporting how far it has come and stopping when cancellationToken is canceled.

public void Save(Stream stream, FormatInfo format, WriterOptions? options, IProgress<SaveProgress>? progress, CancellationToken cancellationToken = default)

Parameters

stream Stream

Where to write, from its current position. It is left open.

format FormatInfo

The format.

options WriterOptions

The format's options, or null for its defaults.

progress IProgress<SaveProgress>

Gets SaveProgress reports, or null.

cancellationToken CancellationToken

Cancels the encode between bands of rows, and inside the codecs that count their own work.

Examples

// Slow encoders (AVIF, JPEG XL, lossy WebP) report how far they have come: once as they start, at most every 250 ms,
// then once more with IsFinal. A canceled token stops the encode and deletes the half-written file.
Progress<SaveProgress> progress = new(p => Console.WriteLine($"{p.Fraction:P0} after {p.Elapsed.TotalSeconds:F1} s"));
image.Save("duck.avif", options: null, progress, cancellationToken);

Exceptions

UnsupportedFormatException

The format has no writer.

ObjectDisposedException

The raster has been disposed.

ArgumentNullException

stream is null.

OperationCanceledException

cancellationToken was canceled.

Save(Stream, string, WriterOptions?)

Encodes the raster in the registered format with this name or file extension, such as "PNG" or ".png".

public void Save(Stream stream, string formatNameOrExtension, WriterOptions? options = null)

Parameters

stream Stream

Where to write, from its current position. It is left open.

formatNameOrExtension string

The format's name or one of its extensions, ignoring case.

options WriterOptions

The format's options, or null for its defaults.

Examples

using FileStream output = File.Create("duck-small.png");
image.Save(output, PngFormat.Info, new PngWriterOptions
{
    Reduce = true,          // the smallest exact form: no alpha if all opaque, gray or a palette when nothing is lost
    CompressionLevel = 9,   // 0 (fastest) to 9 (smallest); 5 by default
});

Exceptions

UnsupportedFormatException

No registered format matches, or it has no writer.

ObjectDisposedException

The raster has been disposed.

ArgumentNullException

stream is null.

Save(Stream, string, WriterOptions?, IProgress<SaveProgress>?, CancellationToken)

Encodes the raster in the named format, reporting progress. See Save(Stream, FormatInfo, WriterOptions?, IProgress<SaveProgress>?, CancellationToken).

public void Save(Stream stream, string formatNameOrExtension, WriterOptions? options, IProgress<SaveProgress>? progress, CancellationToken cancellationToken = default)

Parameters

stream Stream

Where to write, from its current position. It is left open.

formatNameOrExtension string

The format's name or one of its extensions, ignoring case.

options WriterOptions

The format's options, or null for its defaults.

progress IProgress<SaveProgress>

Gets SaveProgress reports, or null.

cancellationToken CancellationToken

Cancels the encode between bands of rows, and inside the codecs that count their own work.

Examples

// Slow encoders (AVIF, JPEG XL, lossy WebP) report how far they have come: once as they start, at most every 250 ms,
// then once more with IsFinal. A canceled token stops the encode and deletes the half-written file.
Progress<SaveProgress> progress = new(p => Console.WriteLine($"{p.Fraction:P0} after {p.Elapsed.TotalSeconds:F1} s"));
image.Save("duck.avif", options: null, progress, cancellationToken);

Exceptions

UnsupportedFormatException

No registered format matches, or it has no writer.

ObjectDisposedException

The raster has been disposed.

ArgumentNullException

stream is null.

OperationCanceledException

cancellationToken was canceled.

Save(string, WriterOptions?)

Encodes the raster to a file, choosing the format from the file extension. An existing file is replaced. If encoding fails, the partly written file is deleted. For Netpbm, the extension also chooses the variant when Kind is Auto: .pbm, .pgm, .ppm, .pam or .pfm.

public void Save(string path, WriterOptions? options = null)

Parameters

path string

The file path.

options WriterOptions

The format's options, or null for its defaults.

Examples

using FileStream output = File.Create("duck-small.png");
image.Save(output, PngFormat.Info, new PngWriterOptions
{
    Reduce = true,          // the smallest exact form: no alpha if all opaque, gray or a palette when nothing is lost
    CompressionLevel = 9,   // 0 (fastest) to 9 (smallest); 5 by default
});

Exceptions

UnsupportedFormatException

No registered format uses the extension, or it has no writer.

ObjectDisposedException

The raster has been disposed.

ArgumentNullException

path is null.

IOException

The file cannot be written.

Save(string, WriterOptions?, IProgress<SaveProgress>?, CancellationToken)

Encodes the raster to a file as Save(string, WriterOptions?) does, reporting progress. If the save fails or is canceled, the partly written file is deleted.

public void Save(string path, WriterOptions? options, IProgress<SaveProgress>? progress, CancellationToken cancellationToken = default)

Parameters

path string

The file path.

options WriterOptions

The format's options, or null for its defaults.

progress IProgress<SaveProgress>

Gets SaveProgress reports, or null.

cancellationToken CancellationToken

Cancels the encode between bands of rows, and inside the codecs that count their own work.

Examples

// Slow encoders (AVIF, JPEG XL, lossy WebP) report how far they have come: once as they start, at most every 250 ms,
// then once more with IsFinal. A canceled token stops the encode and deletes the half-written file.
Progress<SaveProgress> progress = new(p => Console.WriteLine($"{p.Fraction:P0} after {p.Elapsed.TotalSeconds:F1} s"));
image.Save("duck.avif", options: null, progress, cancellationToken);

Exceptions

UnsupportedFormatException

No registered format uses the extension, or it has no writer.

ObjectDisposedException

The raster has been disposed.

ArgumentNullException

path is null.

IOException

The file cannot be written.

OperationCanceledException

cancellationToken was canceled.

SaveAll(IEnumerable<Raster>, Stream, FormatInfo, WriterOptions?)

Writes several rasters to one file in format, in order: each a page of a TIFF. Every format takes one raster, written as Save(Stream, FormatInfo, WriterOptions?) writes it. The rasters are not changed.

public static void SaveAll(IEnumerable<Raster> rasters, Stream stream, FormatInfo format, WriterOptions? options = null)

Parameters

rasters IEnumerable<Raster>

The images to write, at least one.

stream Stream

Where to write, from its current position. It is left open.

format FormatInfo

The format.

options WriterOptions

The format's options, or null for its defaults.

Examples

using RasterList pages = Raster.LoadAll("scan.tif");

// Several rasters make a multi-page TIFF; one raster saves to any format.
Raster.SaveAll(pages, "copy.tif");
Raster.SaveAll([pages[1]], "second.png");

Exceptions

ArgumentException

No raster was given, or more than one to a format that holds one image.

UnsupportedFormatException

The format has no writer.

ObjectDisposedException

A raster has been disposed.

ArgumentNullException

rasters, stream or format is null.

SaveAll(IEnumerable<Raster>, Stream, FormatInfo, WriterOptions?, IProgress<SaveProgress>?, CancellationToken)

Writes several rasters to one file as SaveAll(IEnumerable<Raster>, Stream, FormatInfo, WriterOptions?) does, reporting progress.

public static void SaveAll(IEnumerable<Raster> rasters, Stream stream, FormatInfo format, WriterOptions? options, IProgress<SaveProgress>? progress, CancellationToken cancellationToken = default)

Parameters

rasters IEnumerable<Raster>

The images to write, at least one.

stream Stream

Where to write, from its current position. It is left open.

format FormatInfo

The format.

options WriterOptions

The format's options, or null for its defaults.

progress IProgress<SaveProgress>

Gets SaveProgress reports, or null.

cancellationToken CancellationToken

Cancels the encode between bands of rows, and inside the codecs that count their own work.

Examples

// Slow encoders (AVIF, JPEG XL, lossy WebP) report how far they have come: once as they start, at most every 250 ms,
// then once more with IsFinal. A canceled token stops the encode and deletes the half-written file.
Progress<SaveProgress> progress = new(p => Console.WriteLine($"{p.Fraction:P0} after {p.Elapsed.TotalSeconds:F1} s"));
image.Save("duck.avif", options: null, progress, cancellationToken);

Exceptions

ArgumentException

No raster was given, or more than one to a format that holds one image.

UnsupportedFormatException

The format has no writer.

ObjectDisposedException

A raster has been disposed.

ArgumentNullException

rasters, stream or format is null.

OperationCanceledException

cancellationToken was canceled.

SaveAll(IEnumerable<Raster>, Stream, string, WriterOptions?)

Writes several rasters to one file in the registered format with this name or file extension. See SaveAll(IEnumerable<Raster>, Stream, FormatInfo, WriterOptions?).

public static void SaveAll(IEnumerable<Raster> rasters, Stream stream, string formatNameOrExtension, WriterOptions? options = null)

Parameters

rasters IEnumerable<Raster>

The images to write, at least one.

stream Stream

Where to write, from its current position. It is left open.

formatNameOrExtension string

The format's name or one of its extensions, ignoring case.

options WriterOptions

The format's options, or null for its defaults.

Examples

using RasterList pages = Raster.LoadAll("scan.tif");

// Several rasters make a multi-page TIFF; one raster saves to any format.
Raster.SaveAll(pages, "copy.tif");
Raster.SaveAll([pages[1]], "second.png");

Exceptions

ArgumentException

No raster was given, or more than one to a format that holds one image.

UnsupportedFormatException

No registered format matches, or it has no writer.

ObjectDisposedException

A raster has been disposed.

ArgumentNullException

An argument is null.

SaveAll(IEnumerable<Raster>, Stream, string, WriterOptions?, IProgress<SaveProgress>?, CancellationToken)

Writes several rasters to one file in the named format, reporting progress. See SaveAll(IEnumerable<Raster>, Stream, FormatInfo, WriterOptions?, IProgress<SaveProgress>?, CancellationToken).

public static void SaveAll(IEnumerable<Raster> rasters, Stream stream, string formatNameOrExtension, WriterOptions? options, IProgress<SaveProgress>? progress, CancellationToken cancellationToken = default)

Parameters

rasters IEnumerable<Raster>

The images to write, at least one.

stream Stream

Where to write, from its current position. It is left open.

formatNameOrExtension string

The format's name or one of its extensions, ignoring case.

options WriterOptions

The format's options, or null for its defaults.

progress IProgress<SaveProgress>

Gets SaveProgress reports, or null.

cancellationToken CancellationToken

Cancels the encode between bands of rows, and inside the codecs that count their own work.

Examples

// Slow encoders (AVIF, JPEG XL, lossy WebP) report how far they have come: once as they start, at most every 250 ms,
// then once more with IsFinal. A canceled token stops the encode and deletes the half-written file.
Progress<SaveProgress> progress = new(p => Console.WriteLine($"{p.Fraction:P0} after {p.Elapsed.TotalSeconds:F1} s"));
image.Save("duck.avif", options: null, progress, cancellationToken);

Exceptions

ArgumentException

No raster was given, or more than one to a format that holds one image.

UnsupportedFormatException

No registered format matches, or it has no writer.

ObjectDisposedException

A raster has been disposed.

ArgumentNullException

An argument is null.

OperationCanceledException

cancellationToken was canceled.

SaveAll(IEnumerable<Raster>, string, WriterOptions?)

Writes several rasters to one file, choosing the format from the file extension. An existing file is replaced; if writing fails, the partly written file is deleted. See SaveAll(IEnumerable<Raster>, Stream, FormatInfo, WriterOptions?).

public static void SaveAll(IEnumerable<Raster> rasters, string path, WriterOptions? options = null)

Parameters

rasters IEnumerable<Raster>

The images to write, at least one.

path string

The file path.

options WriterOptions

The format's options, or null for its defaults.

Examples

using RasterList pages = Raster.LoadAll("scan.tif");

// Several rasters make a multi-page TIFF; one raster saves to any format.
Raster.SaveAll(pages, "copy.tif");
Raster.SaveAll([pages[1]], "second.png");

Exceptions

ArgumentException

No raster was given, or more than one to a format that holds one image.

UnsupportedFormatException

No registered format uses the extension, or it has no writer.

ObjectDisposedException

A raster has been disposed.

ArgumentNullException

rasters or path is null.

IOException

The file cannot be written.

SaveAll(IEnumerable<Raster>, string, WriterOptions?, IProgress<SaveProgress>?, CancellationToken)

Writes several rasters to one file, choosing the format from the file extension, reporting progress. If writing fails or is canceled, the partly written file is deleted.

public static void SaveAll(IEnumerable<Raster> rasters, string path, WriterOptions? options, IProgress<SaveProgress>? progress, CancellationToken cancellationToken = default)

Parameters

rasters IEnumerable<Raster>

The images to write, at least one.

path string

The file path.

options WriterOptions

The format's options, or null for its defaults.

progress IProgress<SaveProgress>

Gets SaveProgress reports, or null.

cancellationToken CancellationToken

Cancels the encode between bands of rows, and inside the codecs that count their own work.

Examples

// Slow encoders (AVIF, JPEG XL, lossy WebP) report how far they have come: once as they start, at most every 250 ms,
// then once more with IsFinal. A canceled token stops the encode and deletes the half-written file.
Progress<SaveProgress> progress = new(p => Console.WriteLine($"{p.Fraction:P0} after {p.Elapsed.TotalSeconds:F1} s"));
image.Save("duck.avif", options: null, progress, cancellationToken);

Exceptions

ArgumentException

No raster was given, or more than one to a format that holds one image.

UnsupportedFormatException

No registered format uses the extension, or it has no writer.

ObjectDisposedException

A raster has been disposed.

ArgumentNullException

rasters or path is null.

IOException

The file cannot be written.

OperationCanceledException

cancellationToken was canceled.

SaveAllAsync(IEnumerable<Raster>, Stream, FormatInfo, WriterOptions?, CancellationToken)

Encodes several rasters into a pooled buffer, then writes them to stream asynchronously. See SaveAll(IEnumerable<Raster>, Stream, FormatInfo, WriterOptions?).

public static Task SaveAllAsync(IEnumerable<Raster> rasters, Stream stream, FormatInfo format, WriterOptions? options = null, CancellationToken cancellationToken = default)

Parameters

rasters IEnumerable<Raster>

The images to write, at least one.

stream Stream

Where to write. It is left open.

format FormatInfo

The format.

options WriterOptions

The format's options, or null for its defaults.

cancellationToken CancellationToken

Cancels before encoding and while writing.

Returns

Task

A task that completes when the data is written.

Examples

using RasterList pages = Raster.LoadAll("scan.tif");

// Several rasters make a multi-page TIFF; one raster saves to any format.
Raster.SaveAll(pages, "copy.tif");
Raster.SaveAll([pages[1]], "second.png");

Exceptions

ArgumentException

No raster was given, or more than one to a format that holds one image.

UnsupportedFormatException

The format has no writer.

ObjectDisposedException

A raster has been disposed.

ArgumentNullException

An argument is null.

OperationCanceledException

cancellationToken was canceled.

SaveAsync(Stream, FormatInfo, WriterOptions?, IProgress<SaveProgress>?, CancellationToken)

Encodes the raster and writes it to stream asynchronously, reporting progress. See SaveAsync(Stream, FormatInfo, WriterOptions?, CancellationToken).

public Task SaveAsync(Stream stream, FormatInfo format, WriterOptions? options, IProgress<SaveProgress>? progress, CancellationToken cancellationToken = default)

Parameters

stream Stream

Where to write. It is left open.

format FormatInfo

The format.

options WriterOptions

The format's options, or null for its defaults.

progress IProgress<SaveProgress>

Gets SaveProgress reports, or null.

cancellationToken CancellationToken

Cancels the encode between bands of rows, inside the codecs that count their own work, and while writing.

Returns

Task

A task that completes when the data is written.

Examples

// Slow encoders (AVIF, JPEG XL, lossy WebP) report how far they have come: once as they start, at most every 250 ms,
// then once more with IsFinal. A canceled token stops the encode and deletes the half-written file.
Progress<SaveProgress> progress = new(p => Console.WriteLine($"{p.Fraction:P0} after {p.Elapsed.TotalSeconds:F1} s"));
image.Save("duck.avif", options: null, progress, cancellationToken);

Exceptions

UnsupportedFormatException

No registered format matches, or it has no writer.

ObjectDisposedException

The raster has been disposed.

ArgumentNullException

stream is null.

OperationCanceledException

cancellationToken was canceled.

SaveAsync(Stream, FormatInfo, WriterOptions?, CancellationToken)

Encodes the raster into a pooled buffer, then writes it to stream asynchronously. See Save(Stream, FormatInfo, WriterOptions?).

public Task SaveAsync(Stream stream, FormatInfo format, WriterOptions? options = null, CancellationToken cancellationToken = default)

Parameters

stream Stream

Where to write. It is left open.

format FormatInfo

The format.

options WriterOptions

The format's options, or null for its defaults.

cancellationToken CancellationToken

Cancels before encoding and while writing.

Returns

Task

A task that completes when the data is written.

Examples

// Every Load, Probe and Save has an async twin. Async reads the stream into a pooled buffer first,
// then decodes (decoding is CPU work, so it is synchronous either way).
await using FileStream stream = File.OpenRead("duck.png");
using Raster image = await Raster.LoadAsync(stream, cancellationToken: cancellationToken);
await image.SaveAsync("duck-copy.png", cancellationToken: cancellationToken);

Exceptions

UnsupportedFormatException

No registered format matches, or it has no writer.

ObjectDisposedException

The raster has been disposed.

ArgumentNullException

stream is null.

OperationCanceledException

cancellationToken was canceled.

SaveAsync(Stream, string, WriterOptions?, IProgress<SaveProgress>?, CancellationToken)

Encodes the raster in the named format and writes it asynchronously, reporting progress.

public Task SaveAsync(Stream stream, string formatNameOrExtension, WriterOptions? options, IProgress<SaveProgress>? progress, CancellationToken cancellationToken = default)

Parameters

stream Stream

Where to write. It is left open.

formatNameOrExtension string

The format's name or one of its extensions, ignoring case.

options WriterOptions

The format's options, or null for its defaults.

progress IProgress<SaveProgress>

Gets SaveProgress reports, or null.

cancellationToken CancellationToken

Cancels the encode between bands of rows, inside the codecs that count their own work, and while writing.

Returns

Task

A task that completes when the data is written.

Examples

// Slow encoders (AVIF, JPEG XL, lossy WebP) report how far they have come: once as they start, at most every 250 ms,
// then once more with IsFinal. A canceled token stops the encode and deletes the half-written file.
Progress<SaveProgress> progress = new(p => Console.WriteLine($"{p.Fraction:P0} after {p.Elapsed.TotalSeconds:F1} s"));
image.Save("duck.avif", options: null, progress, cancellationToken);

Exceptions

UnsupportedFormatException

No registered format matches, or it has no writer.

ObjectDisposedException

The raster has been disposed.

ArgumentNullException

stream is null.

OperationCanceledException

cancellationToken was canceled.

SaveAsync(Stream, string, WriterOptions?, CancellationToken)

Encodes the raster in the named format and writes it asynchronously.

public Task SaveAsync(Stream stream, string formatNameOrExtension, WriterOptions? options = null, CancellationToken cancellationToken = default)

Parameters

stream Stream

Where to write. It is left open.

formatNameOrExtension string

The format's name or one of its extensions, ignoring case.

options WriterOptions

The format's options, or null for its defaults.

cancellationToken CancellationToken

Cancels before encoding and while writing.

Returns

Task

A task that completes when the data is written.

Examples

// Every Load, Probe and Save has an async twin. Async reads the stream into a pooled buffer first,
// then decodes (decoding is CPU work, so it is synchronous either way).
await using FileStream stream = File.OpenRead("duck.png");
using Raster image = await Raster.LoadAsync(stream, cancellationToken: cancellationToken);
await image.SaveAsync("duck-copy.png", cancellationToken: cancellationToken);

Exceptions

UnsupportedFormatException

No registered format matches, or it has no writer.

ObjectDisposedException

The raster has been disposed.

ArgumentNullException

stream is null.

OperationCanceledException

cancellationToken was canceled.

SaveAsync(string, WriterOptions?, IProgress<SaveProgress>?, CancellationToken)

Encodes the raster to a file asynchronously, reporting progress. If the save fails or is canceled, the partly written file is deleted.

public Task SaveAsync(string path, WriterOptions? options, IProgress<SaveProgress>? progress, CancellationToken cancellationToken = default)

Parameters

path string

The file path.

options WriterOptions

The format's options, or null for its defaults.

progress IProgress<SaveProgress>

Gets SaveProgress reports, or null.

cancellationToken CancellationToken

Cancels the encode between bands of rows, inside the codecs that count their own work, and while writing.

Returns

Task

A task that completes when the file is written.

Examples

// Slow encoders (AVIF, JPEG XL, lossy WebP) report how far they have come: once as they start, at most every 250 ms,
// then once more with IsFinal. A canceled token stops the encode and deletes the half-written file.
Progress<SaveProgress> progress = new(p => Console.WriteLine($"{p.Fraction:P0} after {p.Elapsed.TotalSeconds:F1} s"));
image.Save("duck.avif", options: null, progress, cancellationToken);

Exceptions

UnsupportedFormatException

No registered format matches, or it has no writer.

ObjectDisposedException

The raster has been disposed.

ArgumentNullException

path is null.

IOException

The file cannot be written.

OperationCanceledException

cancellationToken was canceled.

SaveAsync(string, WriterOptions?, CancellationToken)

Encodes the raster to a file asynchronously, choosing the format from the file extension.

public Task SaveAsync(string path, WriterOptions? options = null, CancellationToken cancellationToken = default)

Parameters

path string

The file path.

options WriterOptions

The format's options, or null for its defaults.

cancellationToken CancellationToken

Cancels before encoding and while writing.

Returns

Task

A task that completes when the file is written.

Examples

// Every Load, Probe and Save has an async twin. Async reads the stream into a pooled buffer first,
// then decodes (decoding is CPU work, so it is synchronous either way).
await using FileStream stream = File.OpenRead("duck.png");
using Raster image = await Raster.LoadAsync(stream, cancellationToken: cancellationToken);
await image.SaveAsync("duck-copy.png", cancellationToken: cancellationToken);

Exceptions

UnsupportedFormatException

No registered format matches, or it has no writer.

ObjectDisposedException

The raster has been disposed.

ArgumentNullException

path is null.

IOException

The file cannot be written.

OperationCanceledException

cancellationToken was canceled.

Signature()

Returns a SHA-256 fingerprint of the pixels, as 64 lowercase hex digits: of the size, the frame count, and each frame's delay and pixels as 16-bit RGBA. Two images get the same signature exactly when they show the same pixels, whatever file or pixel type they came from: an 8-bit image keeps its signature when converted to 16 bits. Metadata other than the delays does not count.

public string Signature()

Returns

string

The signature.

Examples

// The same pixels give the same signature, whatever the file or pixel type: dedupe exact copies.
using Raster<Rgba16> wide = png.As<Rgba16>();
bool same = png.Signature() == wide.Signature();

Exceptions

ObjectDisposedException

The raster has been disposed.

Stack(IReadOnlyList<Raster>, StackMode)

Returns a new raster where each channel of each pixel is the mode (mean, median, min or max) of that channel across the first frames of images, as ImageMagick's -evaluate-sequence does: noise stacking, averaging exposures, background plates. Channels are combined as straight values, so a mean of semi-transparent images averages their colors and their alphas separately. The result has the first raster's pixel type and metadata. It works a few rows at a time, holding one row per input, so stacking 50 large photos needs 50 rows of memory, not 50 photos.

public static Raster Stack(IReadOnlyList<Raster> images, StackMode mode)

Parameters

images IReadOnlyList<Raster>

At least two rasters of the same size, of any pixel types.

mode StackMode

How each channel is combined.

Returns

Raster

The new raster. The caller must dispose it.

Examples

// Average a burst of photos to smooth noise; the median removes things that appear in only a few frames.
using Raster mean = Raster.Stack([first, second, third], StackMode.Mean);
using Raster clean = Raster.Stack([first, second, third], StackMode.Median);

Exceptions

ArgumentNullException

images or one of them is null.

ArgumentException

There are fewer than two rasters, or they differ in size.

ArgumentOutOfRangeException

mode is not defined.

Statistics(int)

Returns the statistics of each channel of a frame and of its luma: minimum, maximum, mean, standard deviation, skewness, kurtosis and entropy on the 0 to 1 scale, as ImageMagick's identify -verbose reports them. Channels are straight, not premultiplied.

public RasterStatistics Statistics(int frame = 0)

Parameters

frame int

The frame, 0 (the default) for the first.

Returns

RasterStatistics

The statistics.

Examples

// Per-channel statistics on the 0 to 1 scale, as identify -verbose prints them.
RasterStatistics stats = photo.Statistics();
Console.WriteLine($"red mean {stats.Red.Mean:F3} ± {stats.Red.StdDev:F3}, luma {stats.Luma.Min:F2} to {stats.Luma.Max:F2}");
bool dark = stats.Luma.Mean < 0.25;

Exceptions

ArgumentOutOfRangeException

frame is not a frame of the image.

ObjectDisposedException

The raster has been disposed.

ToIndexed(PaletteOptions?, int)

Returns one frame as palette indices and the palette they refer to, as a palette PNG would store it: the frame's own colors when they fit, Wu's quantizer otherwise, or the fixed FixedPalette, dithered as the options say.

public IndexedImage ToIndexed(PaletteOptions? options = null, int frame = 0)

Parameters

options PaletteOptions

The color limit, dithering and palette, or null for Default.

frame int

The frame, 0 (the default) for the first.

Returns

IndexedImage

The indexed image. The caller must dispose it.

Examples

// Indices plus palette, for a PDF indexed-color image or a format of your own.
using IndexedImage indexed = photo.ToIndexed(new PaletteOptions { MaxColors = 64 });
byte[] lookup = [.. indexed.Palette.Colors.SelectMany(c => new[] { c.R, c.G, c.B })];
byte[] samples = indexed.Indices.ToArray();

Exceptions

ArgumentOutOfRangeException

frame is not a frame of the image.

ObjectDisposedException

The raster has been disposed.

Transcode(Stream, Stream, FormatInfo, Action<RasterOps>?, ReaderOptions?, WriterOptions?, EgamiContext?)

Transcodes from one stream to another, a band of rows at a time. See Transcode(string, string, Action<RasterOps>?, ReaderOptions?, WriterOptions?, EgamiContext?).

public static void Transcode(Stream input, Stream output, FormatInfo outputFormat, Action<RasterOps>? operations = null, ReaderOptions? readerOptions = null, WriterOptions? writerOptions = null, EgamiContext? context = null)

Parameters

input Stream

The image to read, from its current position. It is left open.

output Stream

Where to write, from its current position. It is left open.

outputFormat FormatInfo

The output format.

operations Action<RasterOps>

The chain, or null to only convert the format.

readerOptions ReaderOptions

How to read, or null for the defaults.

writerOptions WriterOptions

How to write, or null for the format's defaults.

context EgamiContext

The context, or null for Default.

Examples

// A thumbnail of a big file without ever holding the full image: the decoder already shrinks by a whole factor.
Raster.Transcode("egret.png", "thumb.jpg", x => x.Fit(256, 256).Saturation(1.1f));

Exceptions

ArgumentNullException

input, output or outputFormat is null.

NotSupportedException

The chain holds an operation that cannot stream, or a writer option that needs every pixel first.

UnsupportedFormatException

The input's format is not recognized, or the output's has no writer.

CorruptDataException

The input breaks its format's rules.

LimitExceededException

The input exceeds the context's safety limits.

Transcode(Stream, Stream, FormatInfo, Action<RasterOps>?, ReaderOptions?, WriterOptions?, EgamiContext?, IProgress<SaveProgress>?, CancellationToken)

Transcodes from one stream to another, a band of rows at a time, reporting how far the output has come. See Transcode(string, string, Action<RasterOps>?, ReaderOptions?, WriterOptions?, EgamiContext?, IProgress<SaveProgress>?, CancellationToken).

public static void Transcode(Stream input, Stream output, FormatInfo outputFormat, Action<RasterOps>? operations, ReaderOptions? readerOptions, WriterOptions? writerOptions, EgamiContext? context, IProgress<SaveProgress>? progress, CancellationToken cancellationToken = default)

Parameters

input Stream

The image to read, from its current position. It is left open.

output Stream

Where to write, from its current position. It is left open.

outputFormat FormatInfo

The output format.

operations Action<RasterOps>

The chain, or null to only convert the format.

readerOptions ReaderOptions

How to read, or null for the defaults.

writerOptions WriterOptions

How to write, or null for the format's defaults.

context EgamiContext

The context, or null for Default.

progress IProgress<SaveProgress>

Gets SaveProgress reports as the output is written, or null.

cancellationToken CancellationToken

Cancels the work between bands.

Examples

// A progress handler sees the output's rows go out; the token stops the work between bands.
IProgress<SaveProgress> progress = new Progress<SaveProgress>(p => Console.WriteLine($"{p.Fraction:P0}, {p.BytesWritten} bytes"));
Raster.Transcode("egret.png", "egret.jpg", x => x.Fit(1024, 1024), null, null, null, progress, TestContext.Current.CancellationToken);

Exceptions

ArgumentNullException

input, output or outputFormat is null.

NotSupportedException

The chain holds an operation that cannot stream, or a writer option that needs every pixel first.

UnsupportedFormatException

The input's format is not recognized, or the output's has no writer.

CorruptDataException

The input breaks its format's rules.

LimitExceededException

The input exceeds the context's safety limits.

IOException

A file cannot be read or written.

OperationCanceledException

cancellationToken was canceled.

Transcode(string, string, Action<RasterOps>?, ReaderOptions?, WriterOptions?, EgamiContext?)

Decodes a file, runs a short chain of operations and encodes the result, a band of rows at a time, so a huge image never has to exist whole: a thumbnail of a 20,000 × 20,000 PNG takes a few MB. When the chain starts with Fit, Cover or Resize the decoder already shrinks by a whole factor (MinimumSize), and a leading Crop becomes Region, so the result equals loading with those options and running the rest of the chain.

public static void Transcode(string inputPath, string outputPath, Action<RasterOps>? operations = null, ReaderOptions? readerOptions = null, WriterOptions? writerOptions = null, EgamiContext? context = null)

Parameters

inputPath string

The image to read.

outputPath string

The file to write; the format comes from its extension, as in Save(string, WriterOptions?).

operations Action<RasterOps>

The chain, or null to only convert the format.

readerOptions ReaderOptions

How to read, or null for the defaults.

writerOptions WriterOptions

How to write, or null for the format's defaults.

context EgamiContext

The context, or null for Default.

Examples

// A thumbnail of a big file without ever holding the full image: the decoder already shrinks by a whole factor.
Raster.Transcode("egret.png", "thumb.jpg", x => x.Fit(256, 256).Saturation(1.1f));

Remarks

The chain may hold Crop, Resize, Fit and Cover with any filter, FlipHorizontal (and AutoOrient of a mirrored image), and the per-pixel color adjustments (Brightness, Contrast, Saturation, HueRotate, Sepia, Grayscale, Invert, Opacity, ColorMatrix). Anything that needs rows out of order or the whole image (Blur, Rotate, FlipVertical, DrawImage and the rest) throws NotSupportedException before any output is written. An animation keeps its frames when the output format animates; otherwise its first frame is written. Metadata that a format stores after the image data (PNG text after IDAT) is not carried over, since the output's metadata goes before its image data.

Exceptions

ArgumentNullException

inputPath or outputPath is null.

NotSupportedException

The chain holds an operation that cannot stream, or a writer option that needs every pixel first.

UnsupportedFormatException

The input's format is not recognized, or the output's has no writer.

CorruptDataException

The input breaks its format's rules.

LimitExceededException

The input exceeds the context's safety limits.

IOException

A file cannot be read or written.

Transcode(string, string, Action<RasterOps>?, ReaderOptions?, WriterOptions?, EgamiContext?, IProgress<SaveProgress>?, CancellationToken)

Transcodes a file as Transcode(string, string, Action<RasterOps>?, ReaderOptions?, WriterOptions?, EgamiContext?) does, reporting how far the output has come. If the transcode fails or is canceled, the partly written file is deleted.

public static void Transcode(string inputPath, string outputPath, Action<RasterOps>? operations, ReaderOptions? readerOptions, WriterOptions? writerOptions, EgamiContext? context, IProgress<SaveProgress>? progress, CancellationToken cancellationToken = default)

Parameters

inputPath string

The image to read.

outputPath string

The file to write; the format comes from its extension.

operations Action<RasterOps>

The chain, or null to only convert the format.

readerOptions ReaderOptions

How to read, or null for the defaults.

writerOptions WriterOptions

How to write, or null for the format's defaults.

context EgamiContext

The context, or null for Default.

progress IProgress<SaveProgress>

Gets SaveProgress reports as the output is written, or null.

cancellationToken CancellationToken

Cancels the work between bands.

Examples

// A progress handler sees the output's rows go out; the token stops the work between bands.
IProgress<SaveProgress> progress = new Progress<SaveProgress>(p => Console.WriteLine($"{p.Fraction:P0}, {p.BytesWritten} bytes"));
Raster.Transcode("egret.png", "egret.jpg", x => x.Fit(1024, 1024), null, null, null, progress, TestContext.Current.CancellationToken);

Exceptions

ArgumentNullException

inputPath or outputPath is null.

NotSupportedException

The chain holds an operation that cannot stream, or a writer option that needs every pixel first.

UnsupportedFormatException

The input's format is not recognized, or the output's has no writer.

CorruptDataException

The input breaks its format's rules.

LimitExceededException

The input exceeds the context's safety limits.

IOException

A file cannot be read or written.

OperationCanceledException

cancellationToken was canceled.

TranscodeAsync(Stream, Stream, FormatInfo, Action<RasterOps>?, ReaderOptions?, WriterOptions?, EgamiContext?, IProgress<SaveProgress>?, CancellationToken)

Transcodes from one stream to another asynchronously, reporting how far the output has come. See TranscodeAsync(string, string, Action<RasterOps>?, ReaderOptions?, WriterOptions?, EgamiContext?, CancellationToken).

public static Task TranscodeAsync(Stream input, Stream output, FormatInfo outputFormat, Action<RasterOps>? operations, ReaderOptions? readerOptions, WriterOptions? writerOptions, EgamiContext? context, IProgress<SaveProgress>? progress, CancellationToken cancellationToken = default)

Parameters

input Stream

The image to read, from its current position. It is left open.

output Stream

Where to write, from its current position. It is left open.

outputFormat FormatInfo

The output format.

operations Action<RasterOps>

The chain, or null to only convert the format.

readerOptions ReaderOptions

How to read, or null for the defaults.

writerOptions WriterOptions

How to write, or null for the format's defaults.

context EgamiContext

The context, or null for Default.

progress IProgress<SaveProgress>

Gets SaveProgress reports as the output is written, or null.

cancellationToken CancellationToken

Cancels reading, writing and, between bands, the work.

Returns

Task

A task that completes when the output is written.

Examples

// A progress handler sees the output's rows go out; the token stops the work between bands.
IProgress<SaveProgress> progress = new Progress<SaveProgress>(p => Console.WriteLine($"{p.Fraction:P0}, {p.BytesWritten} bytes"));
Raster.Transcode("egret.png", "egret.jpg", x => x.Fit(1024, 1024), null, null, null, progress, TestContext.Current.CancellationToken);

Exceptions

ArgumentNullException

input, output or outputFormat is null.

NotSupportedException

The chain holds an operation that cannot stream, or a writer option that needs every pixel first.

UnsupportedFormatException

The input's format is not recognized, or the output's has no writer.

CorruptDataException

The input breaks its format's rules.

LimitExceededException

The input exceeds the context's safety limits.

IOException

A file cannot be read or written.

OperationCanceledException

cancellationToken was canceled.

TranscodeAsync(Stream, Stream, FormatInfo, Action<RasterOps>?, ReaderOptions?, WriterOptions?, EgamiContext?, CancellationToken)

public static Task TranscodeAsync(Stream input, Stream output, FormatInfo outputFormat, Action<RasterOps>? operations = null, ReaderOptions? readerOptions = null, WriterOptions? writerOptions = null, EgamiContext? context = null, CancellationToken cancellationToken = default)

Parameters

input Stream

The image to read, from its current position. It is left open.

output Stream

Where to write, from its current position. It is left open.

outputFormat FormatInfo

The output format.

operations Action<RasterOps>

The chain, or null to only convert the format.

readerOptions ReaderOptions

How to read, or null for the defaults.

writerOptions WriterOptions

How to write, or null for the format's defaults.

context EgamiContext

The context, or null for Default.

cancellationToken CancellationToken

Cancels reading, writing and, between bands, the work.

Returns

Task

A task that completes when the output is written.

Examples

// On a server: an upload to a 512-pixel PNG preview, streamed both ways.
await using Stream upload = File.OpenRead("egret.png");
await Raster.TranscodeAsync(upload, response, PngFormat.Info, x => x.Fit(512, 512), cancellationToken: TestContext.Current.CancellationToken);

Exceptions

ArgumentNullException

input, output or outputFormat is null.

NotSupportedException

The chain holds an operation that cannot stream, or a writer option that needs every pixel first.

UnsupportedFormatException

The input's format is not recognized, or the output's has no writer.

CorruptDataException

The input breaks its format's rules.

LimitExceededException

The input exceeds the context's safety limits.

OperationCanceledException

cancellationToken was canceled.

TranscodeAsync(string, string, Action<RasterOps>?, ReaderOptions?, WriterOptions?, EgamiContext?, IProgress<SaveProgress>?, CancellationToken)

Transcodes a file asynchronously, reporting how far the output has come. See TranscodeAsync(string, string, Action<RasterOps>?, ReaderOptions?, WriterOptions?, EgamiContext?, CancellationToken).

public static Task TranscodeAsync(string inputPath, string outputPath, Action<RasterOps>? operations, ReaderOptions? readerOptions, WriterOptions? writerOptions, EgamiContext? context, IProgress<SaveProgress>? progress, CancellationToken cancellationToken = default)

Parameters

inputPath string

The image to read.

outputPath string

The file to write; the format comes from its extension.

operations Action<RasterOps>

The chain, or null to only convert the format.

readerOptions ReaderOptions

How to read, or null for the defaults.

writerOptions WriterOptions

How to write, or null for the format's defaults.

context EgamiContext

The context, or null for Default.

progress IProgress<SaveProgress>

Gets SaveProgress reports as the output is written, or null.

cancellationToken CancellationToken

Cancels reading, writing and, between bands, the work.

Returns

Task

A task that completes when the output is written.

Examples

// A progress handler sees the output's rows go out; the token stops the work between bands.
IProgress<SaveProgress> progress = new Progress<SaveProgress>(p => Console.WriteLine($"{p.Fraction:P0}, {p.BytesWritten} bytes"));
Raster.Transcode("egret.png", "egret.jpg", x => x.Fit(1024, 1024), null, null, null, progress, TestContext.Current.CancellationToken);

Exceptions

ArgumentNullException

inputPath or outputPath is null.

NotSupportedException

The chain holds an operation that cannot stream, or a writer option that needs every pixel first.

UnsupportedFormatException

The input's format is not recognized, or the output's has no writer.

CorruptDataException

The input breaks its format's rules.

LimitExceededException

The input exceeds the context's safety limits.

IOException

A file cannot be read or written.

OperationCanceledException

cancellationToken was canceled.

TranscodeAsync(string, string, Action<RasterOps>?, ReaderOptions?, WriterOptions?, EgamiContext?, CancellationToken)

Transcodes a file as Transcode(string, string, Action<RasterOps>?, ReaderOptions?, WriterOptions?, EgamiContext?) does, reading and writing asynchronously. Decoding, the chain and encoding are synchronous, since they are CPU-bound.

public static Task TranscodeAsync(string inputPath, string outputPath, Action<RasterOps>? operations = null, ReaderOptions? readerOptions = null, WriterOptions? writerOptions = null, EgamiContext? context = null, CancellationToken cancellationToken = default)

Parameters

inputPath string

The image to read.

outputPath string

The file to write; the format comes from its extension.

operations Action<RasterOps>

The chain, or null to only convert the format.

readerOptions ReaderOptions

How to read, or null for the defaults.

writerOptions WriterOptions

How to write, or null for the format's defaults.

context EgamiContext

The context, or null for Default.

cancellationToken CancellationToken

Cancels reading, writing and, between bands, the work.

Returns

Task

A task that completes when the output is written.

Examples

// On a server: an upload to a 512-pixel PNG preview, streamed both ways.
await using Stream upload = File.OpenRead("egret.png");
await Raster.TranscodeAsync(upload, response, PngFormat.Info, x => x.Fit(512, 512), cancellationToken: TestContext.Current.CancellationToken);

Exceptions

ArgumentNullException

inputPath or outputPath is null.

NotSupportedException

The chain holds an operation that cannot stream, or a writer option that needs every pixel first.

UnsupportedFormatException

The input's format is not recognized, or the output's has no writer.

CorruptDataException

The input breaks its format's rules.

LimitExceededException

The input exceeds the context's safety limits.

IOException

A file cannot be read or written.

OperationCanceledException

cancellationToken was canceled.

TrimBounds(float, Rgba8?)

Returns the rectangle Trim(float, Rgba8?) would keep: the union over the frames of the pixels farther than tolerance from the border color.

public Rect TrimBounds(float tolerance = 0, Rgba8? color = null)

Parameters

tolerance float

The color distance still counted as border, from 0 (the exact color) to 1 (every color).

color Rgba8?

The border color, or null (the default) for each frame's top-left pixel's.

Returns

Rect

The rectangle, or an empty one when every pixel is border.

Examples

// Cut away the white margin, counting near-white (within 10% by ImageMagick's -fuzz distance) as margin too.
Rect content = scan.TrimBounds(tolerance: 0.1f);
scan.Apply(ops => ops.Trim(tolerance: 0.1f).Fit(400, 400), Ct);

Exceptions

ArgumentOutOfRangeException

tolerance is outside 0..1.

ObjectDisposedException

The raster has been disposed.

Wrap<TPixel>(Memory<byte>, int, int, int, IDisposable?, EgamiContext?)

Creates a raster over bytes with any row stride, such as a frame from a video decoder whose rows are padded to an alignment, without copying. When owner is given, disposing the raster disposes it, so the memory goes back to whoever lent it; otherwise the caller keeps the memory alive while the raster is used. An operation that changes the size gives the raster new memory of its own, and the wrapped memory is released then.

public static Raster<TPixel> Wrap<TPixel>(Memory<byte> memory, int width, int height, int byteStride, IDisposable? owner = null, EgamiContext? context = null) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

memory Memory<byte>

The pixels, row by row.

width int

The width in pixels, at least 1.

height int

The height in pixels, at least 1.

byteStride int

The distance between the starts of consecutive rows, in bytes. 0 means rows are packed.

owner IDisposable

What to dispose when the raster lets go of the memory, or null.

context EgamiContext

The context for later allocations, or null for Default.

Returns

Raster<TPixel>

The raster.

Type Parameters

TPixel

The pixel type.

Exceptions

ArgumentOutOfRangeException

A size is out of range, the stride is shorter than a row, or memory is too short.

Wrap<TPixel>(Memory<TPixel>, int, int, int, EgamiContext?)

Creates a raster over memory the caller owns, without copying. The raster never frees the memory, and the caller must keep it alive while the raster is used. An operation that changes the size gives the raster new memory of its own, so it stops showing the caller's. SafetyLimits are not applied to wrapped memory.

public static Raster<TPixel> Wrap<TPixel>(Memory<TPixel> memory, int width, int height, int stride = 0, EgamiContext? context = null) where TPixel : unmanaged, IPixelType<TPixel>

Parameters

memory Memory<TPixel>

The pixels, row by row.

width int

The width in pixels, at least 1.

height int

The height in pixels, at least 1.

stride int

The distance between the starts of consecutive rows, in pixels. Defaults to width.

context EgamiContext

The context for later allocations, or null for Default.

Returns

Raster<TPixel>

The raster.

Type Parameters

TPixel

The pixel type.

Exceptions

ArgumentOutOfRangeException

A size is out of range, or memory is too short.