Upload optimisation
The upload pipeline most applications actually need: cap the dimensions, re-encode to a modern format, strip the metadata, and see exactly how many bytes that saved. Everything happens on the user's device, so your servers never receive the 8 megapixel original.
Try it
Pipeline
The code
One pipeline, built once and reused for every file: nothing runs until it is executed, so it
is safe to keep in a field. MaxSize only ever shrinks - a small image passes
through untouched instead of being blown up - and the sharpen afterwards recovers the bite
that downscaling takes away. One file at a time, as this page works:
// One pipeline, reused for every file. Nothing runs until it is executed.
var pipeline = ImagePipeline.Create()
.AutoOrient() // honour the phone's rotation sensor
.MaxSize(maxEdge, maxEdge) // never enlarge, only cap
.Sharpen(0.3f); // recover the bite lost to downscaling
foreach (var file in files)
{
using var source = await loader.LoadAsync(file, new DecodeOptions
{
FileName = file.Name,
MaxSize = new Size(maxEdge, maxEdge), // a hint: decode smaller where that is cheap
});
using var processed = await pipeline.ExecuteAsync(source);
var encoded = await exporter.EncodeAsync(processed, new ImageExportOptions
{
Format = ImageFormat.WebP, // offered only where the probe found it
Quality = 0.82,
Metadata = MetadataPolicy.Remove,
});
if (encoded.Length < file.Size) await UploadAsync(file.Name, encoded.Data);
else await UploadOriginalAsync(file); // re-encoding did not help: keep the original
}
For many files at once, the batch API runs the same pipeline with bounded concurrency and a result per file:
Choosing the numbers
- 1920 on the long edge covers a full-width hero on most screens; product thumbnails and avatars want far less.
- WebP at 0.8 is typically 25 to 35% smaller than JPEG at similar quality. Where this browser cannot write it, the format list above simply does not offer it - the list is the capability probe's answer.
- Re-encoding can grow a file. A small or already heavily compressed upload may come out larger; the table says so in red rather than claiming a saving. A real pipeline would keep the original in that case.
- Decode smaller to begin with.
DecodeOptions.MaxSizelets a decoder that can do it cheaply - the browser's, or the JPEG decoder's DCT scaling - hand back a smaller image straight away, which saves memory and time on a 48 megapixel photo; the pipeline'sMaxSizestill makes the result exact. - Check before decoding on a server.
ImageProcessor.Identifyreads the dimensions from the header, so an oversized upload is refused before a byte of pixels is allocated - see the headless API.