Skip to content

Batch processing

The same pipeline over many files with bounded concurrency, live progress, cancellation, and a per-file result rather than one failure aborting the run. This is the headless batch API driving a UI, not a separate code path.

Try it

Live

Pipeline

Each worker holds a decoded image, so this is a memory dial as much as a speed dial.
MaxMemoryBytes: each image is admitted by its expected peak, read from its header before decoding, so small photos run several at a time and a large one waits for room.

The batch API

ProcessBatchAsync is on BmageImageProcessor, which in a browser comes from BmageImageProcessorFactory.GetAsync() once the codec probe has run; on a server, AddBitBmageHeadlessServices registers it directly. Every item comes back with its own outcome - Output, Error or WasCancelled - and StopOnFirstError is opt-in. Cancelling the token throws BmageBatchCancelledException, an OperationCanceledException like any other cancelled call's, whose Result keeps what the batch finished, with WasCancelled on it and on every item it did not get to.

var processor = await processorFactory.GetAsync();

// Each file is read when the batch reaches it, not all of them up front.
var items = files.Select(file => BmageBatchItem.Deferred(async ct =>
{
    await using var stream = file.OpenReadStream(64 * 1024 * 1024, ct);
    using var buffer = new MemoryStream();
    await stream.CopyToAsync(buffer, ct);
    return (ReadOnlyMemory<byte>)buffer.ToArray();
}, file.Name));

try
{
    var result = await processor.ProcessBatchAsync(items, pipeline, new BmageBatchOptions
    {
        MaxConcurrency   = 2,
        MaxMemoryBytes   = 512L * 1024 * 1024,   // optional: admit images by their expected peak
        StopOnFirstError = false,                // one bad file must not lose the rest
        ExportOptions    = exportOptions,
        Progress = new Progress<BmageBatchProgress>(p =>
        {
            completed = p.Completed;
            if (p.Last.Error is { } error) Log(p.Last.FileName, error);
        }),
    }, cancellationToken);

    foreach (var item in result.Succeeded) Save(item.Output!);
    foreach (var item in result.Failed)    Report(item.FileName, item.Error!);
}
catch (BmageBatchCancelledException stopped)
{
    // Stopped by the token: what finished is in the result it carries; these never ran.
    foreach (var item in stopped.Result.Succeeded) Save(item.Output!);
    Retry(stopped.Result.Cancelled.Select(item => item.Item));
}

Size MaxConcurrency against memory, not cores: four workers on 24 megapixel photos is roughly 400 MB of live pixels. Two is a safe default on phones - or set MaxMemoryBytes and let the size of each image decide.

Batches of any length

Three things keep a batch's memory to the images in flight, however many files it has - and this page uses the first two:

  • Deferred items read their file only when the batch reaches them, so a thousand photos are never a thousand files in memory. BmageBatchItem.Deferred takes the function that reads one.
  • MaxMemoryBytes admits images by their expected peak - the file, its pixels, the pipeline's working buffers and an allowance for encoding - in the order they come. One larger than the whole budget runs alone rather than never. For a hard ceiling on what is really allocated, give the processor a BmageBudgetedPixelAllocator as well.
  • ProcessBatchStreamAsync hands each result over as it completes and keeps none of them, so outputs do not pile up either. Its source can itself be an IAsyncEnumerable<BmageBatchItem>, such as files arriving from an upload.
// On a server: a folder of any size, each result saved and let go as soon as it is ready.
var items = Directory.EnumerateFiles(folder, "*.jpg").Select(path =>
    BmageBatchItem.Deferred(async ct => (ReadOnlyMemory<byte>)await File.ReadAllBytesAsync(path, ct), Path.GetFileName(path)));

await foreach (var result in processor.ProcessBatchStreamAsync(items, pipeline, new BmageBatchOptions
{
    MaxConcurrency = 4,
    MaxMemoryBytes = 768L * 1024 * 1024,
    ExportOptions  = new BmageImageExportOptions { Format = BmageImageFormat.Jpeg, Quality = 0.82 },
}, cancellationToken))
{
    if (result.Output is { } output) await File.WriteAllBytesAsync(Path.Combine(outputFolder, result.FileName!), output.Data, cancellationToken);
    else if (result.Error is { } error) logger.LogWarning(error, "Skipped {File}", result.FileName);
}
An unhandled error has occurred. Reload 🗙