Batch Processing

Node

Process multiple images with the same pipeline and configurable concurrency.

batch()

import { batch } from 'imgcraft'

batch(inputs: (string | Buffer)[]): BatchPipeline
import { batch } from 'imgcraft'

batch(inputs: (string | Buffer)[]): BatchPipeline

Create a batch pipeline from an array of file paths or Buffers. Supports the same chainable API as img().

Output methods

Batch pipelines have a different final step — instead of .toBuffer(), use:

.toDir(outputDir: string, options?: ToDirOptions): Promise<BatchResult[]>
.toBuffers(): Promise<Buffer[]>
.toDir(outputDir: string, options?: ToDirOptions): Promise<BatchResult[]>
.toBuffers(): Promise<Buffer[]>

toDir() options

PropTypeDefaultDescription
suffixstring''Append a suffix to the output filename before the extension.
prefixstring''Prepend a prefix to the output filename.
overwritebooleantrueOverwrite existing files.
concurrencynumberos.cpus().lengthMax images processed in parallel.

Examples

Resize and convert a folder

import { batch } from 'imgcraft'
import { glob } from 'glob'

const files = await glob('./photos/*.jpg')

await batch(files)
  .resize(1200)
  .webp({ quality: 85 })
  .toDir('./output', { suffix: '-optimised' })
import { batch } from 'imgcraft'
import { glob } from 'glob'

const files = await glob('./photos/*.jpg')

await batch(files)
  .resize(1200)
  .webp({ quality: 85 })
  .toDir('./output', { suffix: '-optimised' })

Process with progress tracking

const results = await batch(files)
  .resize(800)
  .webp()
  .toDir('./output', { concurrency: 4 })

console.log(`Processed ${results.length} images`)
const results = await batch(files)
  .resize(800)
  .webp()
  .toDir('./output', { concurrency: 4 })

console.log(`Processed ${results.length} images`)

Collect buffers in memory

const buffers = await batch(['a.jpg', 'b.jpg', 'c.jpg'])
  .resize(400)
  .webp({ quality: 80 })
  .toBuffers()
const buffers = await batch(['a.jpg', 'b.jpg', 'c.jpg'])
  .resize(400)
  .webp({ quality: 80 })
  .toBuffers()

BatchResult

Each item in the returned array contains:

FieldTypeDescription
inputstring | BufferOriginal input reference.
outputstringOutput file path (toDir only).
sizenumberOutput file size in bytes.
timingnumberProcessing time in ms.

Concurrency

By default, imgcraft uses one worker per CPU core. Reduce concurrency for AI operations which are more memory-intensive:

await batch(files)
  .removeBackground()
  .png()
  .toDir('./output', { concurrency: 2 })
await batch(files)
  .removeBackground()
  .png()
  .toDir('./output', { concurrency: 2 })