Pipelines
An ImagePipeline is an immutable, ordered list of operations.
Building one does no work: it is a description of an edit that you can inspect, store, reuse
across images and threads, and execute when you are ready.
Build one
Every choice below is a builder call. Each returns a new pipeline and leaves the old one as it was - which is what makes a pipeline safe to keep in a static field and reuse for every upload.
Pipeline
Auto orient → Resize(600x600, Max) → Vibrance → Sharpen
After the optimiser
Auto orient → Resize(600x600, Max) → Vibrance → Sharpen
Geometry
Adjustments and filters
Brightness(0) and Contrast(0) do nothing, and the optimiser
drops them - watch the step count.
Building and inspecting
A pipeline knows its output size, the transform it applies to coordinates and the memory it will need, all without touching a pixel - which is how the playground above prints its output size before anything runs, and how the editor keeps annotations on what they mark.
var pipeline = ImagePipeline.Create()
.AutoOrient()
.MaxSize(1920, 1920)
.Sharpen(0.3f);
Console.WriteLine(pipeline);
// Auto orient → Resize(1920x1920, Max) → Sharpen
Console.WriteLine(pipeline.GetOutputSize(new Size(4000, 3000)));
// {Width=1920, Height=1440} ← computed without touching a single pixel
// TryGetOutputSize answers false, rather than throwing, for steps that need the pixels.
if (pipeline.TryGetOutputSize(size, out var output)) { /* ... */ }
// Where a point of the source ends up, for geometric pipelines: overlays follow with it.
if (pipeline.TryGetTransform(size, out var matrix)) { var moved = Vector2.Transform(point, matrix); }
// The memory a run will hold at its peak, before it runs.
var estimate = pipeline.EstimateMemory(new Size(6000, 4000));
Console.WriteLine($"{estimate.PeakBytes / 1048576} MB at the peak, {estimate.OutputBytes / 1048576} MB of result");
It is also an IReadOnlyList<IImageOperation>, edited the way an immutable list
is - every call returns a new pipeline:
var edit = ImagePipeline.Create().AutoOrient().Brightness(0.1f).Sharpen(0.3f);
edit = edit.Replace(1, new BrightnessAdjustment(0.2f)); // change a step without redoing the rest
edit = edit.Insert(1, new ContrastAdjustment(0.1f));
edit = edit.RemoveAt(edit.Count - 1);
var look = ImagePipeline.Create().Sepia(0.6f).Vignette(0.4f);
var final = edit.Concat(look); // two pipelines, one run
var fromList = ImagePipeline.From(savedOperations); // any IEnumerable<IImageOperation>Executing
using var result = await pipeline.ExecuteAsync(source, new PipelineExecutionOptions
{
CancellationToken = token,
Progress = new Progress<double>(p => _percent = p),
});
The source is never modified, and the returned buffer is yours to dispose.
ExecuteAsync yields to the scheduler between operations so a single-threaded
WebAssembly UI can repaint; Execute is the synchronous form, for use off the UI
thread or on small images.
| Option | Meaning |
|---|---|
Allocator | Where intermediate buffers come from. Defaults to the shared pool. |
Limits | Safety limits applied to every buffer allocated during the run. |
CancellationToken | Checked between operations and periodically inside them, typically every few rows. |
Progress | Receives 0 to 1 across the whole run, with each operation's own progress mapped into its slice. |
Optimize | Run the optimiser first. Default true. |
MaxDegreeOfParallelism | Threads each operation may spread its rows over. One by default; the pixels are identical at any number. See Performance. |
YieldBetweenOperations | Yield to the scheduler between steps. Default true. |
YieldCallback | How to yield, if the default Task.Yield is not right for your host. |
Failures are wrapped with context rather than surfacing bare - an
ImageException names the operation and its step, such as
Operation 'Crop' (step 2 of 4) failed: Crop rectangle ... does not intersect the image
(800x600).
Geometry
pipeline.AutoOrient() // apply the EXIF rotation so the image is upright
.Crop(x, y, width, height)
.CropToAspect(AspectRatio.Ratio16x9, Anchor.Center)
.Resize(width, height, mode, filter, anchor, background)
.MaxSize(1920, 1080) // shrink to fit, never enlarge
.Cover(512, 512, Anchor.Top) // fill exactly, cropping the overflow
.Rotate(12.5, background) // arbitrary angle, canvas expands
.Rotate(12.5, expandCanvas: false) // ...or keeps its size, corners cut off
.Straighten(-3.5) // level a tilt and crop the empty corners
.Orient(Orientation.Rotate90) // lossless, no resampling
.FlipHorizontal()
.FlipVertical()
.Skew(10, 0)
.CanvasSize(1200, 1200, Anchor.Top, Rgba32.White)
.Pad(40, Rgba32.White); // a 40 pixel border
AutoOrient is almost always the first thing you want. Phones record rotation in
EXIF rather than rotating the pixels, so an image that looks right in a photo viewer will
appear sideways on a canvas unless it is applied. The browser decoder applies it during
decoding; AutoOrient handles the cases where it has not been.
| Operation | What it does |
|---|---|
Crop, CropToAspect, SmartCrop | A rectangle you give, the largest one of an aspect ratio at an anchor, or the one around the subject. |
Resize, MaxSize, Cover | Scale in one of the six modes below, with the resampling filter of your choice. |
Orient, FlipHorizontal, FlipVertical | The eight lossless orientations: pixels move, nothing is resampled. |
Rotate | Any angle. The canvas grows to hold the corners, filled with background, unless expandCanvas: false keeps the original size. |
Straighten | Levels a tilt of up to 45° and crops to the largest rectangle of the image's aspect ratio the turned image covers, so no corner is left empty. |
CanvasSize, Pad | Grows or shrinks the canvas without scaling the image: an exact size with an anchor, or margins on each side (negative ones cut in). A border, a square canvas for a product shot, room for a caption. |
Skew, AffineTransformOperation, PerspectiveTransformOperation | Shear by angles, any 2D matrix, or a four-corner warp - PerspectiveTransformOperation.Straighten turns a photographed document or screen into a rectangle. |
ContentBounds.Find | Not an operation but the measurement behind a trim: the rectangle inside transparent or uniform borders, to hand to Crop. |
Trimming is an analysis rather than an operation on purpose: an operation must know its output size without seeing the pixels, which is what lets documents, memory estimates and annotation placement work before anything runs.
// Margins one side at a time; a negative margin cuts into the image.
pipeline.Pad(left: 0, top: 120, right: 0, bottom: 0, background: Rgba32.Black);
// Any 2D matrix, and a four-corner warp: a photographed page made rectangular.
pipeline.Apply(new AffineTransformOperation(Matrix3x2.CreateRotation(0.1f) * Matrix3x2.CreateScale(1.2f)));
pipeline.Apply(PerspectiveTransformOperation.Straighten(pageCorners, new Size(1240, 1754)));
// Trim: measure the borders, then crop to what is inside them.
var content = ContentBounds.Find(image, new TrimOptions { Mode = TrimMode.Transparent, Padding = 8 });
if (content is { } bounds) pipeline = pipeline.Crop(bounds);
The six resize modes
For a 1000 × 500 source asked to fit 400 × 400:
| Mode | Result | Behaviour |
|---|---|---|
Fit | 400 × 200 | Scale proportionally to fit inside. The default. |
Contain | 400 × 400 | Like Fit, then pad to exactly the target with background. |
Cover | 400 × 400 | Scale to fill, then crop the overflow according to anchor. |
Stretch | 400 × 400 | Ignore the aspect ratio. |
Max | 400 × 200 | Like Fit, but never enlarge a smaller image - the right choice for an upload cap. |
Min | 800 × 400 | Scale so both dimensions are at least the target. |
Resampling filters
| Filter | Use it for |
|---|---|
Auto | The default. Lanczos3 for downscaling, bicubic for upscaling. |
Box | Fast area averaging; excellent for large reductions. |
Bilinear | Fast, moderate quality. |
Bicubic | Good general purpose quality. |
Lanczos3 | Sharpest downscaling, slowest. |
NearestNeighbor | Pixel art, or wherever hard edges must survive. |
Large reductions automatically get an exact integer box prepass before the chosen filter, which is why a 24 megapixel thumbnail takes 52 ms rather than 368 ms. It is transparent and quality-neutral.
Smart cropping
A fixed anchor is wrong most of the time: centre-cropping a portrait to a square routinely cuts
off the top of a head. SmartCrop scores candidate positions on a small downscaled
copy using local detail, colour saturation and skin-like hue, then picks the best. It is a
heuristic, not face recognition - when you do have a detector, hand it the rectangle. The
Avatar page compares it with the fixed anchors.
pipeline.SmartCrop(AspectRatio.Square);
// With a face detector of your own:
var crop = SmartCrop.FindCrop(image, AspectRatio.Square, mustInclude: faceRectangle);
pipeline.Crop(crop.Rectangle);Adjustments and filters
pipeline.Brightness(0.1f).Contrast(0.15f).Saturation(-0.2f).Hue(15)
.Exposure(0.5f).Gamma(1.2f).Temperature(0.2f).Tint(-0.1f)
.Vibrance(0.3f).ShadowsHighlights(0.2f, -0.15f).Opacity(0.9f)
.Grayscale().Sepia(0.8f).Invert().Posterize(6).Threshold(0.5f)
.Blur(4f).Sharpen(0.5f).Pixelate(12).Noise(0.05f)
.DenoiseMedian(1).Vignette(0.4f)
.ColorMatrix(myMatrix);
pipeline.AutoLevels(); // stretch the tonal range
pipeline.AutoLevels(perChannel: true); // also neutralise a colour cast
pipeline.AutoContrast(targetMean: 0.5f); // gentler: move the mean luminance towards a target
// A region confines a filter - this is how redaction works.
pipeline.Pixelate(14, new Rectangle(40, 120, 300, 40));
// Movement and texture.
pipeline.MotionBlur(distance: 24, angle: -15).HighPass(radius: 3);
pipeline.Apply(ConvolutionFilter.Emboss());
pipeline.Apply(new ConvolutionFilter([0, -1, 0, -1, 5, -1, 0, -1, 0], 3, 3)); // any kernel
Amounts are consistently in [-1, 1] with 0 meaning no change, except where another unit is
natural: Exposure is in stops, Hue in degrees, Gamma is
a positive multiplier and Blur a radius in pixels. Filters that take a region only
touch that region, which is how redaction works.
AutoLevels stretches the tonal range - the most useful single fix - ignoring the
darkest and brightest 0.5% by default, so one hot pixel cannot define the white point, and it
leaves a flat histogram alone rather than amplifying it into noise.
Colour and tone
The tools a photo editor's develop panel has: white balance picked from something neutral or found automatically, the whites and blacks points, one colour range at a time, and the mixers behind black and white conversions and duotones.
// White balance: from a pixel that should be neutral, or found automatically.
var grey = ColorSampler.Sample(image, new Point(120, 80), radius: 3); // the eyedropper
pipeline.WhiteBalance(grey);
pipeline.AutoWhiteBalance(strength: 0.8f);
// The ends of the tonal range, and the whole curve.
pipeline.WhitesBlacks(whites: 0.2f, blacks: -0.15f);
pipeline.Apply(new LevelsAdjustment(inputBlack: 0.05f, inputWhite: 0.95f, gamma: 1.1f));
pipeline.Apply(CurveOperation.FromFunction(x => x * x * (3 - 2 * x), name: "S-curve"));
// One colour range at a time: bluer, richer skies; calmer greens.
pipeline.Hsl(HueBand.Blues, hue: -8, saturation: 0.3f, lightness: -0.2f)
.Hsl(HueBand.Greens, saturation: -0.25f);
// Channel mixers, black and white from chosen channels, and tinting.
pipeline.ChannelMixer(red: new(1.1f, -0.1f, 0), green: new(0, 1, 0), blue: new(0, 0.1f, 0.9f));
pipeline.BlackAndWhite(red: 0.6f, green: 0.3f, blue: 0.1f); // a red filter on black and white film
pipeline.Colorize(hue: 30, saturation: 0.35f);
// Map luminance onto colours: two of them, or any gradient.
pipeline.Duotone(shadows: new Rgba32(24, 32, 88), highlights: new Rgba32(250, 214, 140));
pipeline.Apply(new GradientMapOperation([(0f, Rgba32.Black), (0.5f, new Rgba32(200, 40, 90)), (1f, new Rgba32(255, 230, 120))]));
Everything there is
| Group | Builder calls |
|---|---|
| Light | Brightness, Contrast, Exposure (stops), Gamma, ShadowsHighlights, WhitesBlacks, AutoLevels, AutoContrast; levels and curves through LevelsAdjustment and CurveOperation |
| Colour | Saturation, Vibrance, Hue (degrees), Temperature, Tint, WhiteBalance, AutoWhiteBalance, Hsl (one of eight hue bands), ChannelMixer, Colorize, ColorMatrix, Opacity |
| Looks | Grayscale, BlackAndWhite (a channel mix), Sepia, Invert, Posterize, Threshold, Duotone and any GradientMapOperation, Vignette |
| Detail | Blur, MotionBlur (a distance and an angle), Sharpen (unsharp mask), HighPass, DenoiseMedian, Noise, Pixelate; any kernel through ConvolutionFilter, with Emboss and EdgeDetect built in |
| Selective | Masked runs any of the above through a mask, ApplyMask cuts the alpha to one, and RemoveBackground clears a plain backdrop - see Layers and masks and Retouching |
The optimiser
It runs by default. Every rewrite keeps the framing and the output size exactly; all but one keep the pixels too, or make them more accurate.
| Rule | Effect |
|---|---|
| Drop identities | Brightness(0) and friends disappear. |
| Merge crops | Two crops become one. |
| Merge orientations | Rotate 90 twice becomes rotate 180; two horizontal flips vanish entirely. |
| Drop a superseded resize | A resize whose result the next resize entirely replaces is skipped, so the survivor resamples from the original pixels - sharper, and the one rule whose pixels differ from an unoptimised run. |
| Fuse resize with a following crop | One resample that computes only the surviving region, 2.4× faster. |
| Fuse per-pixel runs | One pass over the pixels instead of one per adjustment. |
// Three no-ops and two crops.
var pipeline = ImagePipeline.Create()
.Brightness(0)
.Crop(10, 10, 200, 200)
.Crop(5, 5, 100, 100)
.Contrast(0);
pipeline.Optimize(new Size(400, 400));
// Crop(15,15,100,100)
Fusing per-pixel operations removes the intermediate 8-bit rounding that separate execution
performs, so a fused chain is more accurate, not merely faster. Turn the optimiser off
with new PipelineExecutionOptions { Optimize = false } if you are comparing
behaviour, but there is no reason to in production.
Previewing at another resolution
ForScale rescales every operation - crop rectangles, blur radii, pixelation block
sizes, stroke widths, font sizes. This is how the editor previews full-resolution edits on a
proxy and gets the same picture, and why there is one rendering path rather than a fast one and
an accurate one that drift apart.
var preview = pipeline.ForScale(0.25);Custom operations
Implement IImageOperation, or derive from PointOperation if your
operation maps each pixel independently - then it joins the single-pass run with the
adjustments around it for free. Override CanProcessRowsConcurrently when
ProcessRow only reads its own fields, so it can spread over threads too, and give
it a JSON codec so documents that use it save and replay.