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
FrameCount
Gets the number of frames. Always at least 1.
public abstract int FrameCount { get; }
Property Value
Height
Gets the height in pixels.
public int Height { get; }
Property Value
Layout
Gets the memory layout of the pixel type.
public abstract PixelLayoutInfo Layout { get; }
Property Value
Metadata
Gets the raster's metadata.
public RasterMetadata Metadata { get; }
Property Value
Width
Gets the width in pixels.
public int Width { get; }
Property Value
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
imagesIReadOnlyList<Raster>At least one raster, of any sizes and pixel types.
axisAxisSide by side (the default) or stacked.
spacingintThe gap between neighbours, in pixels, 0 or more.
backgroundRgba8The color of gaps and of the space around smaller images; transparent black by default.
alignmentAlignmentWhere 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
imagesor one of them is null.- ArgumentException
imagesis 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
buildAction<RasterOps>Records the chain.
cancellationTokenCancellationTokenCancels between steps and between bands of rows.
Exceptions
- ArgumentNullException
buildis 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
cancellationTokenwas 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
TToThe 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
colorRgba8The color to select, with its alpha.
tolerancefloatThe color distance, from 0 (the exact color) to 1 (every color).
Returns
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
toleranceis 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
redRasterThe red channel.
greenRasterThe green channel.
blueRasterThe blue channel.
alphaRasterThe alpha channel, or null for opaque.
Returns
- Raster<TPixel>
The new raster. The caller must dispose it.
Type Parameters
TPixelThe 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
aRasterThe first image.
bRasterThe second image, the same size.
optionsCompareOptionsThe 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
aorbis 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
targetColorProfileThe encoding to convert to.
optionsColorTransformOptionsThe intent and black point compensation, or null for the defaults.
Returns
- Raster<TTo>
The new raster. The caller must dispose it.
Type Parameters
TToThe 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
targetis 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
frameintThe 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
frameis 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
widthintThe width in pixels, at least 1.
heightintThe height in pixels, at least 1.
contextEgamiContext
Returns
- Raster<TPixel>
The new raster. The caller must dispose it.
Type Parameters
TPixelThe pixel type.
Exceptions
- ArgumentOutOfRangeException
widthorheightis 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
widthintThe width in pixels, at least 1.
heightintThe height in pixels, at least 1.
fillTPixelThe color of every pixel.
contextEgamiContext
Returns
- Raster<TPixel>
The new raster. The caller must dispose it.
Type Parameters
TPixelThe pixel type.
Exceptions
- ArgumentOutOfRangeException
widthorheightis 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
buildAction<RasterOps>Records the chain.
cancellationTokenCancellationTokenCancels between steps and between bands of rows.
Returns
- Raster
The new raster, in the same pixel type. The caller must dispose it.
Exceptions
- ArgumentNullException
buildis 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
cancellationTokenwas 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
maxAnglefloatThe 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
maxAngleis 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
aRasterThe first image.
bRasterThe second image, the same size.
styleDifferenceStyleWhat to draw. Defaults to Highlight.
optionsDifferenceOptions
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
aorbis null.- ArgumentException
The images differ in size.
- ArgumentOutOfRangeException
styleis 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
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
countintThe most colors wanted, 1 to 128. Defaults to 5. Fewer come back when the image has fewer distinct colors.
optionsDominantColorOptions
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
countis 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
thresholdfloatThe 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
thresholdis 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
channelColorChannelThe 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
channelis 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
channelColorChannelThe channel.
Returns
- Raster<TPixel>
The new raster. The caller must dispose it.
Type Parameters
TPixelThe 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
channelis 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
methodThresholdMethodHow the level is found. Defaults to Otsu.
modeThresholdModeWhat 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
seedPointWhere the region starts.
tolerancefloatThe color distance, from 0 (the seed's exact color) to 1 (every color).
connectivityConnectivityWhether the region spreads to the four side neighbours or also the four diagonal ones.
Returns
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,
toleranceis outside 0..1, orconnectivityis 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
limitintThe most colors wanted; the scan stops once there are more.
frameintThe 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
limitis negative, orframeis 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
imagesIReadOnlyList<Raster>At least one raster, of any sizes and pixel types.
columnsintThe cells per row, at least 1.
cellSize?The cell size, or null (the default) for the largest image's width and height.
spacingintThe gap between cells, in pixels, 0 or more.
backgroundRgba8The color of gaps and empty cell space; transparent black by default.
filterResampleFilterThe 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
imagesor one of them is null.- ArgumentException
imagesis 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
levelintThe level, from 2 to 16. Defaults to 8 (512 × 512, a 64³ table).
Returns
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
levelis 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
levelintThe level, from 2 to 16. Defaults to 8.
Returns
- Raster<TPixel>
The image; the caller disposes it.
Type Parameters
TPixelThe 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
levelis 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
channelColorChannelThe channel, or Luminance for the Rec. 709 luma.
binsintThe number of bins, 2 to 65,536. Defaults to 256, one per 8-bit value.
frameintThe 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
tolerancefloatHow far apart the channels may be, from 0 (equal) to 1.
frameintThe frame, or -1 (the default) for every frame.
Returns
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
frameintThe frame, or -1 (the default) for every frame.
Returns
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
frameis 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
streamStreamThe encoded image. It is read from its current position and left open; a seekable stream ends just past the image.
contextEgamiContextoptionsReaderOptions
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
streamis 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
streamStreamThe encoded image. It is read from its current position and left open; a seekable stream ends just past the image.
formatFormatInfoThe format to read with. It need not be registered in the context.
contextEgamiContextoptionsReaderOptions
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
formathas no reader.- CorruptDataException
The data breaks the format's rules, including data of another format.
- LimitExceededException
The image breaks a safety limit.
- ArgumentNullException
streamorformatis 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
dataReadOnlyMemory<byte>The encoded image.
contextEgamiContextoptionsReaderOptions
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
dataReadOnlyMemory<byte>The encoded image.
formatFormatInfoThe format to read with. It need not be registered in the context.
contextEgamiContextoptionsReaderOptions
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
formathas no reader.- CorruptDataException
The data breaks the format's rules, including data of another format.
- LimitExceededException
The image breaks a safety limit.
- ArgumentNullException
formatis null.
Load(string, EgamiContext?, ReaderOptions?)
Loads an image file. See Load(Stream, EgamiContext?, ReaderOptions?).
public static Raster Load(string path, EgamiContext? context = null, ReaderOptions? options = null)
Parameters
pathstringThe file path.
contextEgamiContextoptionsReaderOptions
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
pathis 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
streamStreamThe encoded file. It is read from its current position and left open; a stream that cannot seek is read whole first.
contextEgamiContextoptionsReaderOptions
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
streamis 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
streamStreamThe encoded file.
formatFormatInfoThe format to read with. It need not be registered in the context.
contextEgamiContextoptionsReaderOptions
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
formathas 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
streamorformatis 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
dataReadOnlyMemory<byte>The encoded file.
contextEgamiContextoptionsReaderOptions
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
dataReadOnlyMemory<byte>The encoded file.
formatFormatInfoThe format to read with. It need not be registered in the context.
contextEgamiContextoptionsReaderOptions
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
formathas 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
formatis 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
pathstringThe file path.
contextEgamiContextoptionsReaderOptions
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
pathis 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
streamStreamThe encoded file.
contextEgamiContextoptionsReaderOptionscancellationTokenCancellationTokenCancels 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
streamis null.- OperationCanceledException
cancellationTokenwas 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
pathstringThe file path.
contextEgamiContextoptionsReaderOptionscancellationTokenCancellationTokenCancels 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
pathis null.- FileNotFoundException
The file does not exist.
- IOException
The file cannot be read.
- OperationCanceledException
cancellationTokenwas 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
streamStreamThe encoded file.
contextEgamiContextoptionsReaderOptionscancellationTokenCancellationTokenCancels reading and decoding.
Returns
- Task<RasterList>
The images, in the file's order. The caller must dispose the list.
Type Parameters
TPixelThe 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
streamis null.- OperationCanceledException
cancellationTokenwas 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
pathstringThe file path.
contextEgamiContextoptionsReaderOptionscancellationTokenCancellationTokenCancels reading and decoding.
Returns
- Task<RasterList>
The images, in the file's order. The caller must dispose the list.
Type Parameters
TPixelThe 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
pathis null.- FileNotFoundException
The file does not exist.
- IOException
The file cannot be read.
- OperationCanceledException
cancellationTokenwas 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
streamStreamThe encoded file.
contextEgamiContextoptionsReaderOptions
Returns
- RasterList
The images, in the file's order. The caller must dispose the list.
Type Parameters
TPixelThe 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
streamis 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
streamStreamThe encoded file.
formatFormatInfoThe format to read with. It need not be registered in the context.
contextEgamiContextoptionsReaderOptions
Returns
- RasterList
The images, in the file's order. The caller must dispose the list.
Type Parameters
TPixelThe 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
formathas 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
streamorformatis 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
dataReadOnlyMemory<byte>The encoded file.
contextEgamiContextoptionsReaderOptions
Returns
- RasterList
The images, in the file's order. The caller must dispose the list.
Type Parameters
TPixelThe 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
dataReadOnlyMemory<byte>The encoded file.
formatFormatInfoThe format to read with. It need not be registered in the context.
contextEgamiContextoptionsReaderOptions
Returns
- RasterList
The images, in the file's order. The caller must dispose the list.
Type Parameters
TPixelThe 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
formathas 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
formatis 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
pathstringThe file path.
contextEgamiContextoptionsReaderOptions
Returns
- RasterList
The images, in the file's order. The caller must dispose the list.
Type Parameters
TPixelThe 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
pathis 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
streamStreamThe encoded image.
contextEgamiContextoptionsReaderOptionscancellationTokenCancellationTokenCancels reading and, between rows, decoding.
Returns
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
streamis null.- OperationCanceledException
cancellationTokenwas canceled.
LoadAsync(string, EgamiContext?, ReaderOptions?, CancellationToken)
Loads an image file asynchronously. See LoadAsync(Stream, EgamiContext?, ReaderOptions?, CancellationToken).
public static Task<Raster> LoadAsync(string path, EgamiContext? context = null, ReaderOptions? options = null, CancellationToken cancellationToken = default)
Parameters
pathstringThe file path.
contextEgamiContextoptionsReaderOptionscancellationTokenCancellationTokenCancels reading and decoding.
Returns
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
pathis null.- FileNotFoundException
The file does not exist.
- IOException
The file cannot be read.
- OperationCanceledException
cancellationTokenwas 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
streamStreamThe encoded image.
contextEgamiContextoptionsReaderOptionscancellationTokenCancellationTokenCancels reading and decoding.
Returns
Type Parameters
TPixelThe 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
streamis null.- OperationCanceledException
cancellationTokenwas 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
pathstringThe file path.
contextEgamiContextoptionsReaderOptionscancellationTokenCancellationTokenCancels reading and decoding.
Returns
Type Parameters
TPixelThe 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
pathis null.- FileNotFoundException
The file does not exist.
- IOException
The file cannot be read.
- OperationCanceledException
cancellationTokenwas 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
streamStreamThe encoded image. It is read from its current position and left open.
targetRaster<TPixel>Where to decode: the size the image decodes to, after Region and MinimumSize. Only its first frame is written.
contextEgamiContextoptionsReaderOptions
Type Parameters
TPixelThe 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
targetis 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
streamortargetis 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
dataReadOnlyMemory<byte>The encoded image.
targetRaster<TPixel>Where to decode: the size the image decodes to. Only its first frame is written.
contextEgamiContextoptionsReaderOptions
Type Parameters
TPixelThe 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
targetis 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
targetis 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
pathstringThe file path.
targetRaster<TPixel>Where to decode: the size the image decodes to. Only its first frame is written.
contextEgamiContextoptionsReaderOptions
Type Parameters
TPixelThe 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
targetis 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
pathortargetis 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
streamStreamThe encoded image.
contextEgamiContextoptionsReaderOptions
Returns
- Raster<TPixel>
The raster. The caller must dispose it.
Type Parameters
TPixelThe 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
streamis 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
streamStreamThe encoded image.
formatFormatInfoThe format to read with. It need not be registered in the context.
contextEgamiContextoptionsReaderOptions
Returns
- Raster<TPixel>
The raster. The caller must dispose it.
Type Parameters
TPixelThe 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
formathas no reader.- CorruptDataException
The data breaks the format's rules, including data of another format.
- LimitExceededException
The image breaks a safety limit.
- ArgumentNullException
streamorformatis 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
dataReadOnlyMemory<byte>The encoded image.
contextEgamiContextoptionsReaderOptions
Returns
- Raster<TPixel>
The raster. The caller must dispose it.
Type Parameters
TPixelThe 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
dataReadOnlyMemory<byte>The encoded image.
formatFormatInfoThe format to read with. It need not be registered in the context.
contextEgamiContextoptionsReaderOptions
Returns
- Raster<TPixel>
The raster. The caller must dispose it.
Type Parameters
TPixelThe 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
formathas no reader.- CorruptDataException
The data breaks the format's rules, including data of another format.
- LimitExceededException
The image breaks a safety limit.
- ArgumentNullException
formatis 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
pathstringThe file path.
contextEgamiContextoptionsReaderOptions
Returns
- Raster<TPixel>
The raster. The caller must dispose it.
Type Parameters
TPixelThe 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
pathis 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
linkedboolWhether 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
linkedboolWhether 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
blackfloatThe fraction of pixels that becomes black, from 0 to 1.
whitefloatThe fraction that becomes white, from 0 to 1; with
blackless than 1.linkedboolWhether 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
modeEqualizeModeWhat 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
modeis 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
methodWhiteBalanceMethodHow 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
methodis 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
streamStreamThe encoded image. A seekable stream ends just past the bytes read.
contextEgamiContextoptionsReaderOptionsReader 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
streamis 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
streamStreamThe encoded image. A seekable stream ends just past the bytes read.
formatFormatInfoThe format to read with. It need not be registered in the context.
contextEgamiContextoptionsReaderOptionsReader 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
formathas no reader.- CorruptDataException
The header breaks the format's rules, including data of another format.
- LimitExceededException
The header breaks a safety limit.
- ArgumentNullException
streamorformatis 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
dataReadOnlyMemory<byte>The encoded image.
contextEgamiContextoptionsReaderOptionsReader 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
dataReadOnlyMemory<byte>The encoded image.
formatFormatInfoThe format to read with. It need not be registered in the context.
contextEgamiContextoptionsReaderOptionsReader 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
formathas no reader.- CorruptDataException
The header breaks the format's rules, including data of another format.
- LimitExceededException
The header breaks a safety limit.
- ArgumentNullException
formatis 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
pathstringThe file path.
contextEgamiContextoptionsReaderOptionsReader 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
pathis 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
streamStreamThe encoded image.
contextEgamiContextoptionsReaderOptionsReader 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.
cancellationTokenCancellationTokenCancels 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
streamis null.- OperationCanceledException
cancellationTokenwas 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
pathstringThe file path.
contextEgamiContextoptionsReaderOptionsReader 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.
cancellationTokenCancellationTokenCancels 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
pathis null.- FileNotFoundException
The file does not exist.
- IOException
The file cannot be read.
- OperationCanceledException
cancellationTokenwas 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
streamStreamWhere to write, from its current position. It is left open.
formatFormatInfoThe format.
optionsWriterOptionsThe 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
streamis 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
streamStreamWhere to write, from its current position. It is left open.
formatFormatInfoThe format.
optionsWriterOptionsThe format's options, or null for its defaults.
progressIProgress<SaveProgress>Gets SaveProgress reports, or null.
cancellationTokenCancellationTokenCancels 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
streamis null.- OperationCanceledException
cancellationTokenwas 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
streamStreamWhere to write, from its current position. It is left open.
formatNameOrExtensionstringThe format's name or one of its extensions, ignoring case.
optionsWriterOptionsThe 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
streamis 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
streamStreamWhere to write, from its current position. It is left open.
formatNameOrExtensionstringThe format's name or one of its extensions, ignoring case.
optionsWriterOptionsThe format's options, or null for its defaults.
progressIProgress<SaveProgress>Gets SaveProgress reports, or null.
cancellationTokenCancellationTokenCancels 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
streamis null.- OperationCanceledException
cancellationTokenwas 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
pathstringThe file path.
optionsWriterOptionsThe 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
pathis 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
pathstringThe file path.
optionsWriterOptionsThe format's options, or null for its defaults.
progressIProgress<SaveProgress>Gets SaveProgress reports, or null.
cancellationTokenCancellationTokenCancels 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
pathis null.- IOException
The file cannot be written.
- OperationCanceledException
cancellationTokenwas 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
rastersIEnumerable<Raster>The images to write, at least one.
streamStreamWhere to write, from its current position. It is left open.
formatFormatInfoThe format.
optionsWriterOptionsThe 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,streamorformatis 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
rastersIEnumerable<Raster>The images to write, at least one.
streamStreamWhere to write, from its current position. It is left open.
formatFormatInfoThe format.
optionsWriterOptionsThe format's options, or null for its defaults.
progressIProgress<SaveProgress>Gets SaveProgress reports, or null.
cancellationTokenCancellationTokenCancels 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,streamorformatis null.- OperationCanceledException
cancellationTokenwas 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
rastersIEnumerable<Raster>The images to write, at least one.
streamStreamWhere to write, from its current position. It is left open.
formatNameOrExtensionstringThe format's name or one of its extensions, ignoring case.
optionsWriterOptionsThe 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
rastersIEnumerable<Raster>The images to write, at least one.
streamStreamWhere to write, from its current position. It is left open.
formatNameOrExtensionstringThe format's name or one of its extensions, ignoring case.
optionsWriterOptionsThe format's options, or null for its defaults.
progressIProgress<SaveProgress>Gets SaveProgress reports, or null.
cancellationTokenCancellationTokenCancels 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
cancellationTokenwas 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
rastersIEnumerable<Raster>The images to write, at least one.
pathstringThe file path.
optionsWriterOptionsThe 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
rastersorpathis 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
rastersIEnumerable<Raster>The images to write, at least one.
pathstringThe file path.
optionsWriterOptionsThe format's options, or null for its defaults.
progressIProgress<SaveProgress>Gets SaveProgress reports, or null.
cancellationTokenCancellationTokenCancels 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
rastersorpathis null.- IOException
The file cannot be written.
- OperationCanceledException
cancellationTokenwas 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
rastersIEnumerable<Raster>The images to write, at least one.
streamStreamWhere to write. It is left open.
formatFormatInfoThe format.
optionsWriterOptionsThe format's options, or null for its defaults.
cancellationTokenCancellationTokenCancels 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
cancellationTokenwas 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
streamStreamWhere to write. It is left open.
formatFormatInfoThe format.
optionsWriterOptionsThe format's options, or null for its defaults.
progressIProgress<SaveProgress>Gets SaveProgress reports, or null.
cancellationTokenCancellationTokenCancels 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
streamis null.- OperationCanceledException
cancellationTokenwas 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
streamStreamWhere to write. It is left open.
formatFormatInfoThe format.
optionsWriterOptionsThe format's options, or null for its defaults.
cancellationTokenCancellationTokenCancels 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
streamis null.- OperationCanceledException
cancellationTokenwas 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
streamStreamWhere to write. It is left open.
formatNameOrExtensionstringThe format's name or one of its extensions, ignoring case.
optionsWriterOptionsThe format's options, or null for its defaults.
progressIProgress<SaveProgress>Gets SaveProgress reports, or null.
cancellationTokenCancellationTokenCancels 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
streamis null.- OperationCanceledException
cancellationTokenwas 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
streamStreamWhere to write. It is left open.
formatNameOrExtensionstringThe format's name or one of its extensions, ignoring case.
optionsWriterOptionsThe format's options, or null for its defaults.
cancellationTokenCancellationTokenCancels 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
streamis null.- OperationCanceledException
cancellationTokenwas 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
pathstringThe file path.
optionsWriterOptionsThe format's options, or null for its defaults.
progressIProgress<SaveProgress>Gets SaveProgress reports, or null.
cancellationTokenCancellationTokenCancels 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
pathis null.- IOException
The file cannot be written.
- OperationCanceledException
cancellationTokenwas 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
pathstringThe file path.
optionsWriterOptionsThe format's options, or null for its defaults.
cancellationTokenCancellationTokenCancels 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
pathis null.- IOException
The file cannot be written.
- OperationCanceledException
cancellationTokenwas 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
imagesIReadOnlyList<Raster>At least two rasters of the same size, of any pixel types.
modeStackModeHow 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
imagesor one of them is null.- ArgumentException
There are fewer than two rasters, or they differ in size.
- ArgumentOutOfRangeException
modeis 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
frameintThe 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
frameis 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
optionsPaletteOptionsThe color limit, dithering and palette, or null for Default.
frameintThe 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
frameis 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
inputStreamThe image to read, from its current position. It is left open.
outputStreamWhere to write, from its current position. It is left open.
outputFormatFormatInfoThe output format.
operationsAction<RasterOps>The chain, or null to only convert the format.
readerOptionsReaderOptionsHow to read, or null for the defaults.
writerOptionsWriterOptionsHow to write, or null for the format's defaults.
contextEgamiContext
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,outputoroutputFormatis 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
inputStreamThe image to read, from its current position. It is left open.
outputStreamWhere to write, from its current position. It is left open.
outputFormatFormatInfoThe output format.
operationsAction<RasterOps>The chain, or null to only convert the format.
readerOptionsReaderOptionsHow to read, or null for the defaults.
writerOptionsWriterOptionsHow to write, or null for the format's defaults.
contextEgamiContextprogressIProgress<SaveProgress>Gets SaveProgress reports as the output is written, or null.
cancellationTokenCancellationTokenCancels 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,outputoroutputFormatis 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
cancellationTokenwas 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
inputPathstringThe image to read.
outputPathstringThe file to write; the format comes from its extension, as in Save(string, WriterOptions?).
operationsAction<RasterOps>The chain, or null to only convert the format.
readerOptionsReaderOptionsHow to read, or null for the defaults.
writerOptionsWriterOptionsHow to write, or null for the format's defaults.
contextEgamiContext
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
inputPathoroutputPathis 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
inputPathstringThe image to read.
outputPathstringThe file to write; the format comes from its extension.
operationsAction<RasterOps>The chain, or null to only convert the format.
readerOptionsReaderOptionsHow to read, or null for the defaults.
writerOptionsWriterOptionsHow to write, or null for the format's defaults.
contextEgamiContextprogressIProgress<SaveProgress>Gets SaveProgress reports as the output is written, or null.
cancellationTokenCancellationTokenCancels 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
inputPathoroutputPathis 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
cancellationTokenwas 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
inputStreamThe image to read, from its current position. It is left open.
outputStreamWhere to write, from its current position. It is left open.
outputFormatFormatInfoThe output format.
operationsAction<RasterOps>The chain, or null to only convert the format.
readerOptionsReaderOptionsHow to read, or null for the defaults.
writerOptionsWriterOptionsHow to write, or null for the format's defaults.
contextEgamiContextprogressIProgress<SaveProgress>Gets SaveProgress reports as the output is written, or null.
cancellationTokenCancellationTokenCancels 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,outputoroutputFormatis 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
cancellationTokenwas canceled.
TranscodeAsync(Stream, Stream, FormatInfo, Action<RasterOps>?, ReaderOptions?, WriterOptions?, EgamiContext?, CancellationToken)
Transcodes from one stream to another asynchronously. See TranscodeAsync(string, string, 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
inputStreamThe image to read, from its current position. It is left open.
outputStreamWhere to write, from its current position. It is left open.
outputFormatFormatInfoThe output format.
operationsAction<RasterOps>The chain, or null to only convert the format.
readerOptionsReaderOptionsHow to read, or null for the defaults.
writerOptionsWriterOptionsHow to write, or null for the format's defaults.
contextEgamiContextcancellationTokenCancellationTokenCancels 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,outputoroutputFormatis 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
cancellationTokenwas 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
inputPathstringThe image to read.
outputPathstringThe file to write; the format comes from its extension.
operationsAction<RasterOps>The chain, or null to only convert the format.
readerOptionsReaderOptionsHow to read, or null for the defaults.
writerOptionsWriterOptionsHow to write, or null for the format's defaults.
contextEgamiContextprogressIProgress<SaveProgress>Gets SaveProgress reports as the output is written, or null.
cancellationTokenCancellationTokenCancels 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
inputPathoroutputPathis 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
cancellationTokenwas 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
inputPathstringThe image to read.
outputPathstringThe file to write; the format comes from its extension.
operationsAction<RasterOps>The chain, or null to only convert the format.
readerOptionsReaderOptionsHow to read, or null for the defaults.
writerOptionsWriterOptionsHow to write, or null for the format's defaults.
contextEgamiContextcancellationTokenCancellationTokenCancels 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
inputPathoroutputPathis 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
cancellationTokenwas 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
tolerancefloatThe color distance still counted as border, from 0 (the exact color) to 1 (every color).
colorRgba8?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
toleranceis 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
memoryMemory<byte>The pixels, row by row.
widthintThe width in pixels, at least 1.
heightintThe height in pixels, at least 1.
byteStrideintThe distance between the starts of consecutive rows, in bytes. 0 means rows are packed.
ownerIDisposableWhat to dispose when the raster lets go of the memory, or null.
contextEgamiContext
Returns
- Raster<TPixel>
The raster.
Type Parameters
TPixelThe pixel type.
Exceptions
- ArgumentOutOfRangeException
A size is out of range, the stride is shorter than a row, or
memoryis 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
memoryMemory<TPixel>The pixels, row by row.
widthintThe width in pixels, at least 1.
heightintThe height in pixels, at least 1.
strideintThe distance between the starts of consecutive rows, in pixels. Defaults to
width.contextEgamiContext
Returns
- Raster<TPixel>
The raster.
Type Parameters
TPixelThe pixel type.
Exceptions
- ArgumentOutOfRangeException
A size is out of range, or
memoryis too short.