Formats
PNG, JPEG, BMP, GIF, WebP and AVIF are decoded by C# that runs anywhere, and PNG, JPEG, BMP and WebP encoded by it; AVIF is written only by the browser's own codecs. Support varies by browser, version and platform, so Bmage probes instead of assuming - and refuses to pass off a substitute as the format you asked for.
Encode one image every way
The same 1200 × 800 scene, encoded at quality 0.82 in each format. A format this browser cannot write is attempted anyway, to show what the exporter does about it.
What decodes and encodes where
| Format | Managed decode | Managed encode | Browser decode | Browser encode |
|---|---|---|---|---|
| PNG | yes | yes | yes | yes |
| JPEG | yes | yes | yes | yes |
| BMP | yes | yes | yes | via managed |
| GIF | first frame | no | first frame | no |
| WebP | yes; first frame of an animation | lossy and lossless | yes | usually, lossy only |
| AVIF | yes; no colour management | no | usually | rarely |
| SVG | refused | no | refused | no |
"Managed" means pure C#, working anywhere including a server. "Browser" means the platform's own codecs, the only way to write AVIF. In WebAssembly the browser codec wins when both are available, because it is hardware accelerated and colour manages; the managed codecs remain the fallback, which is what makes prerendering and server-side use work. Over Interactive Server and in a Blazor Hybrid app it is the other way round, because pixels a browser codec touches cross the circuit or the WebView: the managed codecs decode and encode first, the browser decodes only what they reject, what is over the limits and wide gamut photos, and it encodes only AVIF and whatever else the managed codecs cannot write. The Capabilities page shows the probe's answer for this browser.
Never assume, always probe
Asked to encode a format they cannot write, browsers silently produce a PNG instead. Bmage probes by actually encoding a pixel and checking what came back, and detects the substitution at export time too.
var capabilities = await capabilityProvider.GetAsync();
if (capabilities.CanEncode(ImageFormat.Avif)) { /* ... */ }
if (capabilities.SupportsWebP) { /* ... */ }
try
{
var avif = await exporter.EncodeAsync(image, ImageExportOptions.Avif);
}
catch (ImageCapabilityException ex)
{
// "This browser cannot encode Avif; it produced image/png instead. Check
// ImageCapabilities.CanEncode before exporting and fall back to a supported format."
}
If you would rather degrade than handle an exception, ask for a preference order:
var encoded = await exporter.EncodeWithFallbackAsync(
image,
[ImageFormat.Avif, ImageFormat.WebP, ImageFormat.Jpeg],
new ImageExportOptions { Quality = 0.82 });
Console.WriteLine(encoded.Format); // whichever one this browser can actually writeChoosing a format
| Situation | Choose |
|---|---|
| Photographs, broad compatibility | JPEG at 0.8 to 0.85 |
| Photographs, modern browsers | WebP at 0.8, roughly 25 to 35% smaller than JPEG at similar quality |
| Anything needing transparency | WebP, or PNG for lossless |
| Screenshots, diagrams, flat colour | PNG |
| Smallest possible, where supported | AVIF, but always with a fallback |
| Clipboard | PNG; most browsers accept nothing else |
Circular avatars need transparency, so prefer WebP or PNG there - a lossy opaque format shows the corners. The Avatar page switches its fallback for exactly that reason.
Quality and size budgets
var encoded = await exporter.EncodeAsync(image, new ImageExportOptions
{
Format = ImageFormat.WebP,
Quality = 0.9,
MaxFileSize = 100 * 1024,
MinQuality = 0.5,
MaxFileSizeStrategy = MaxFileSizeStrategy.QualityThenDimensions,
});
Console.WriteLine($"{encoded.Length} bytes at quality {encoded.Quality}");
MaxFileSize bisects on quality first, down to MinQuality, then shrinks
the dimensions if the strategy allows it. The quality actually used is reported on the result,
so you can show it. When the target is impossible you get an ImageEncodeException
explaining what the smallest attempt produced, rather than a silently oversized file.
| Strategy | Behaviour |
|---|---|
QualityThenDimensions | Lower quality first, then shrink. The default. |
QualityOnly | Never change dimensions; throw if the budget cannot be met. |
DimensionsOnly | Keep quality fixed and shrink. |
PNG is lossless, so quality does not apply; PngCompressionLevel trades time for size
instead, from 0 to 9. Level 1 is several times faster than the default 6 for a modestly larger file -
right for a preview on screen for a moment, while 6 suits the file the user keeps.
Getting the result out
An EncodedImage is the bytes, with the format, dimensions and quality used. From there it
goes wherever your code sends it - nothing is uploaded by the library.
var encoded = await exporter.EncodeAsync(image, new ImageExportOptions { Format = ImageFormat.Png, PngCompressionLevel = 1 });
byte[] bytes = encoded.Data; // upload it, store it
using var stream = encoded.AsStream(); // hand it to an API that takes a stream
Console.WriteLine($"{encoded.Width}×{encoded.Height} {encoded.MimeType}, {encoded.Length} bytes");
var url = await exporter.CreateObjectUrlAsync(encoded); // <img src="@url">
await exporter.ReleaseObjectUrlAsync(url); // when the preview goes away
await exporter.DownloadAsync(encoded, "photo"); // extension from the format
var saved = await exporter.SaveAsAsync(encoded, "photo"); // a save dialog where there is one
await exporter.CopyToClipboardAsync(encoded); // paste it into a chat or a document
SaveAsAsync uses the browser's save dialog where the File System Access API exists and
falls back to a plain download elsewhere, returning false when the user cancels. The clipboard takes
PNG in practice, and ImageCapabilities.SupportsClipboardWrite says whether it can be
written at all.
Transparency without an alpha channel
JPEG has no alpha channel. Exporting a transparent image as JPEG composites it over
ImageExportOptions.Background, which defaults to white - without it, browsers
composite over black, which is rarely what anyone wants. Set it explicitly when white is wrong
for your page.
new ImageExportOptions { Format = ImageFormat.Jpeg, Background = new Rgba32(18, 18, 20) }Format detection
Content is trusted over file names and content types, because both can be wrong or hostile.
ImageProcessor.Identify reads dimensions from the header without decoding any
pixels, which is how an oversized upload is rejected before anything is allocated.
DisplaySize accounts for EXIF orientation, so a portrait photo from a phone
reports portrait dimensions even though its stored pixels are landscape.
var format = ImageFormats.Detect(bytes); // magic bytes
var byName = ImageFormats.FromFileName("photo.JPG"); // convenience only
var byMime = ImageFormats.FromMimeType("image/webp"); // convenience only
var info = processor.Identify(bytes);
if (info is null) return Error("Not a supported image.");
if ((long)info.Width * info.Height > 40_000_000) return Error("Too large.");
Console.WriteLine($"{info.Width}×{info.Height} {info.Format}, displays as {info.DisplaySize}");GIF and SVG
GIF decodes its first frame, with palettes, interlacing and transparency; animation is out of scope, as it is for an animated WebP, and GIF encoding is supported by no browser canvas and is not implemented - use WebP or PNG.
SVG is refused with an explanatory error rather than rasterised. Rendering untrusted SVG can execute embedded scripts and fetch remote resources, and a library cannot make that safe on the caller's behalf. If you control the SVG, rasterise it yourself and pass the pixels.