Hosting models
Bmage's engine is C# that runs wherever .NET does, and its browser integration runs wherever Blazor has a browser to talk to. What changes between hosts is where the pixels live - and, in a prerendered app, when there is a browser at all.
What works where
| Model | What works | What to know |
|---|---|---|
| Blazor WebAssembly | Everything | The intended home. Processing runs on the user's device with no network involved. |
Blazor Web App, InteractiveWebAssembly | Everything | Same as above once the component is interactive. This site. |
Blazor Web App, InteractiveAuto | Everything once interactive | The first visit runs on the server while the runtime downloads - see Interactive Server. |
Blazor Web App, InteractiveServer | Everything | Works, but pixels cross the circuit. |
| Blazor Hybrid (MAUI, WPF, Windows Forms) | Everything | .NET runs in the app and reaches the WebView over its interop bridge; no network involved. Saving a file on Android and iOS is the app's job. |
| Prerendering | Managed codecs only | No browser exists yet. Call browser features from OnAfterRenderAsync. |
| ASP.NET Core, console, worker | Headless API | AddBitBmageHeadlessServices. Managed codecs only, no JavaScript. |
In a Blazor Web App
A Web App has two projects and both build a service container: the client's runs in the browser, and the server's prerenders every page before the runtime has downloaded. Every component is instantiated in both, so both have to register Bmage - or the prerender fails with a missing-service exception. This site keeps the registration in one extension method in the client project and calls it from both.
The client project
Reference Bit.Bmage.Blazor from the client, which is the project that runs in the
browser.
// Client/Extensions/IServiceCollectionExtensions.cs
using Bit.Bmage;
namespace Microsoft.Extensions.DependencyInjection;
public static class IServiceCollectionExtensions
{
// Called by the client's Program.cs and by the server's, for the prerender pass.
public static IServiceCollection AddDemoServices(this IServiceCollection services)
{
services.AddBitBmageServices(options =>
{
options.MaxSourceBytes = 64 * 1024 * 1024;
options.Limits = ImageLimits.Default with { MaxPixels = 80_000_000 };
});
return services;
}
}
The server project
The server references the client project, registers the same services for its prerender pass, and maps the client's assembly so its pages are routable.
// Server/Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorComponents()
.AddInteractiveWebAssemblyComponents();
// The prerender pass instantiates the client's components in this container,
// so it has to register the very same services the WebAssembly container does.
builder.Services.AddDemoServices();
var app = builder.Build();
app.UseAntiforgery();
app.MapStaticAssets();
app.MapRazorComponents<App>()
.AddInteractiveWebAssemblyRenderMode()
.AddAdditionalAssemblies(typeof(Client._Imports).Assembly);
app.Run();
App.razor
The editor's stylesheet goes in the head, and the app renders in
InteractiveWebAssembly (or InteractiveAuto), so the image work
happens on the user's device.
<head>
...
<link rel="stylesheet" href="_content/Bit.Bmage.Blazor/bit-bmage-editor.css" />
<HeadOutlet @rendermode="InteractiveWebAssembly" />
</head>
<body>
<Routes @rendermode="InteractiveWebAssembly" />
<script src="_framework/blazor.web.js"></script>
</body>Prerendering
During prerendering there is no browser, so IJSRuntime cannot be used. Rather
than throwing, IImageCapabilityProvider.GetAsync returns the managed capability
set with Environment set to Prerendering, so a prerendered page still
renders something sensible and detects properly once interactive. Move browser work to
OnAfterRenderAsync or an event handler.
@inject IImageCapabilityProvider Capabilities
@if (_capabilities is null)
{
<p>Probing this browser...</p>
}
@code {
private ImageCapabilities? _capabilities;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
// OnAfterRenderAsync never runs during prerendering, and RendererInfo says
// whether this render is the interactive one.
if (!firstRender || !RendererInfo.IsInteractive) return;
_capabilities = await Capabilities.GetAsync();
StateHasChanged();
}
}
Buttons on a prerendered page are visible before the runtime that answers them has loaded. This
site disables its own until RendererInfo.IsInteractive is true, and its layout
carries the same fact as data-interactive, which is what its end-to-end tests
wait for before dropping a file on a page.
Interactive Server
Everything works, because JavaScript interop works over the circuit. What changes is where the bytes travel: the browser decodes an image and the pixels are streamed to the server for processing, then the result is streamed back to be encoded. For a 4000 × 3000 photo that is 48 MB in each direction - unremarkable on a local network, not over a poor mobile connection. If images are central to an Interactive Server app:
- Constrain the working size aggressively:
options.MaxInteractiveDimension = 1200. - Use
DecodeOptions.MaxSizeso the browser downscales before the pixels are sent at all. - Prefer the headless API on the server for bulk work, and use the browser only for what needs a browser.
- Consider whether the image-heavy pages belong in the client project, with WebAssembly.
IImageCapabilityProvider reports ImageEnvironment.BrowserServer there,
so code can adapt.
Standalone WebAssembly
One project, no prerendering: register the services in Program.cs and link the
stylesheet from wwwroot/index.html.
// Program.cs
using Bit.Bmage;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.AddBitBmageServices();
await builder.Build().RunAsync();
<!-- wwwroot/index.html -->
<head>
...
<link rel="stylesheet" href="_content/Bit.Bmage.Blazor/bit-bmage-editor.css" />
</head>Blazor Hybrid (MAUI, WPF, Windows Forms)
Everything works. The components run in compiled .NET inside the app's own process and render
into a WebView, which Bmage reaches over JavaScript interop - the same position as Interactive
Server, so IImageCapabilityProvider reports ImageEnvironment.BrowserServer
and picks codecs the same way: images are decoded and encoded by .NET in the app, and AVIF
exports and photos whose colours need colour management by the WebView. Nothing crosses a network,
but those pixels and the editor's previews are copied through the WebView's message channel.
There is one container, and the WebView is there from the first render: register the services once, next to the WebView, and link the stylesheet from the page the WebView hosts. The pixel loops run on the device's CPU rather than in WebAssembly, so an image can have every core.
// MauiProgram.cs
using Bit.Bmage;
var builder = MauiApp.CreateBuilder();
builder.UseMauiApp<App>();
builder.Services.AddMauiBlazorWebView();
builder.Services.AddBitBmageServices(options =>
{
options.MaxDegreeOfParallelism = Environment.ProcessorCount;
});
return builder.Build();
<!-- wwwroot/index.html -->
<head>
...
<link rel="stylesheet" href="_content/Bit.Bmage.Blazor/bit-bmage-editor.css" />
</head>
Saving a file is the platform's job on mobile. DownloadAsync hands the file to the
WebView: WebView2 on Windows saves it as Edge would, but Android's WebView and iOS's WKWebView
leave downloads to the app. There, encode and save the bytes with the platform's APIs:
var encoded = await Exporter.EncodeWithFallbackAsync(image, [ImageFormat.WebP, ImageFormat.Jpeg]);
var path = Path.Combine(FileSystem.CacheDirectory, "photo" + encoded.Extension);
await File.WriteAllBytesAsync(path, encoded.Data);
await Share.Default.RequestAsync(new ShareFileRequest
{
Title = "Save the image",
File = new ShareFile(path)
});
- Which formats the WebView codes depends on its engine - Chromium in WebView2 and on Android, Safari's in WKWebView on iOS and Mac Catalyst. The probe measures the one the app runs in, so pick formats with
ChooseEncodableFormatorEncodeWithFallbackAsync. - The MAUI template interprets .NET in Debug builds, for Hot Reload. Judge performance on a Release build.
- Samples/MAUI is a working app over the same pages as the Web App samples.
Lazy loading on WebAssembly
BmageEditor also works without the registration, so a WebAssembly app can download
Bmage only when someone opens the editor. When ImageLoader is not registered, the
editor builds every service it needs itself, once per browser connection, with the
BitBmageOptions the app registered or the defaults. Mark both assemblies as lazy
loaded, and load them before the editor first renders:
<!-- The browser project's .csproj -->
<ItemGroup>
<BlazorWebAssemblyLazyLoad Include="Bit.Bmage.wasm" />
<BlazorWebAssemblyLazyLoad Include="Bit.Bmage.Blazor.wasm" />
</ItemGroup>
@* App.razor: the router waits for OnNavigateAsync before it renders the page. *@
@using Microsoft.AspNetCore.Components.WebAssembly.Services
@inject LazyAssemblyLoader LazyAssemblyLoader
<Router AppAssembly="typeof(App).Assembly" OnNavigateAsync="OnNavigateAsync">
...
</Router>
@code {
private async Task OnNavigateAsync(NavigationContext context)
{
// The page with the editor on it: fetch Bmage before it renders.
if (context.Path == "edit")
await LazyAssemblyLoader.LoadAssembliesAsync(["Bit.Bmage.wasm", "Bit.Bmage.Blazor.wasm"]);
}
}
- Leave
AddBitBmageServicesout of that project'sProgram.cs: calling it references Bmage's types before the assemblies are there. - Code of your own that injects
ImageLoaderorImageExporterneeds the registration, so lazy loading suits an app whose only use of Bmage is the editor. - In a Blazor Web App only the browser lazy loads. Give
RoutestheInteractiveWebAssemblyorInteractiveAutorender mode inApp.razor, so the router - and itsOnNavigateAsync- runs in the browser. The server project loads Bmage with the rest of the app and keeps itsAddBitBmageServices(), and registersLazyAssemblyLoader, which the router's file injects while it is prerendered there:builder.Services.AddScoped<LazyAssemblyLoader>(). - Do not lazy load in an AOT build. AOT compiles every assembly into
dotnet.native.wasm, so there is nothing left to download later, and lazy loading an AOT-compiled assembly can fail at startup.
Web Workers and a Content Security Policy
In the browser, decoding, encoding and building the editor's working copy run in a small pool of
Web Workers loaded from _content/Bit.Bmage.Blazor/bit-bmage-worker.js, so the page's
thread - which on WebAssembly is also .NET's - keeps painting while a photo decodes. A Content Security
Policy that lists sources explicitly has to allow them, with worker-src 'self' or a
script-src 'self' it falls back to; Blob URLs are never used for workers.
Content-Security-Policy: worker-src 'self'
Nothing breaks without them: where workers are blocked or the browser has no
OffscreenCanvas, the same work runs on the page's thread. Cap the pool, or turn it
off, with BitBmageOptions.MaxCodecWorkers - see
Performance.
Compile ahead of time
Bmage is tuned for Blazor's default IL interpreter, but what stays in .NET still runs 4 to 12 times faster when the browser project is compiled ahead of time - see Performance for the measurements.
<PropertyGroup>
<RunAOTCompilation>true</RunAOTCompilation>
</PropertyGroup>
- It needs the
wasm-toolsworkload:dotnet workload install wasm-tools. - It only applies to
dotnet publish.dotnet runand the debugger always use the interpreter, so judge performance on a published build. - The download grows (the runtime's
dotnet.native.wasmwent from 2.9 MB to 13 MB uncompressed) and publishing takes minutes rather than seconds.
This site switches it on for a Release publish only - so its deployment is compiled ahead of
time while a plain dotnet build -c Release still works on a machine without the
workload. In a Web App you publish the server project and the client is compiled as part of it;
either pass -p:RunAOTCompilation=true to that publish, or condition it in the
client project the way this site does.
Without a browser
On a server, in a console app or a background worker, register the headless services instead.
There is no JavaScript and no probing, so ImageProcessor is registered directly.
Only the managed codecs exist: PNG, JPEG, BMP and GIF for decoding; PNG, JPEG and BMP for
encoding.
using Bit.Bmage;
builder.Services.AddBitBmageHeadlessServices(options =>
{
options.Limits = ImageLimits.Default with { MaxPixels = 30_000_000 };
});
// Then inject ImageProcessor wherever you need it.
app.MapPost("/thumbnail", async (IFormFile file, ImageProcessor processor) => { /* ... */ });
The Headless API page runs the same engine in your browser with no components, and shows a complete upload endpoint.