image-blob-reduce

repository·master·Indexed 43 days ago

https://github.com/nodeca/image-blob-reduce

A wrapper for the pica library providing high-quality image resizing for blobs in the browser. Version 5.0.1 allows developers to downscale image blobs (such as those from file inputs) while maintaining JPEG orientation and metadata. It features a customizable pipeline with .toBlob() and .toCanvas() methods, as well as hooks and plugins to extend resizing logic.

Tokens
2K
Snippets
11
Records
14
Agent score
6%

What's inside image-blob-reduce

  1. Quickstart: Downscale a blob

    master

    You can quickly downscale an image blob by creating a reducer instance and calling .toBlob(). The max option limits the longest side of the image to the specified pixel value.

    import imageBlobReduce from 'image-blob-reduce'
    
    const reduce = imageBlobReduce()
    
    // ...
    
    reduce
      .toBlob(image_blob, { max: 1000 })
      .then(blob => { 
      // Use the downscaled blob
    })
  2. Initialize image-blob-reduce via factory function or class

    master

    You can use the imageBlobReduce factory function or instantiate the ImageBlobReduce class directly. Both accept an optional ImageBlobReduceOptions object to provide a custom pica instance.

    import imageBlobReduce from 'image-blob-reduce';
    
    // Using the factory function
    const reducer = imageBlobReduce();
    
    // Using the class constructor
    import { ImageBlobReduce } from 'image-blob-reduce';
    const reducer = new ImageBlobReduce();
    import imageBlobReduce from 'image-blob-reduce';
    const reducer = imageBlobReduce();
  3. Customize the reducer logic

    master

    You can customize the reducer by inheriting from the ImageBlobReduce class, adding hooks, or overriding internal methods on an instance.

    Example: Force output to always be JPEG with 0.8 quality

    import imageBlobReduce from 'image-blob-reduce'
    
    const reducer = imageBlobReduce()
    
    reducer._create_blob = function (env) {
      return this.pica.toBlob(env.out_canvas, 'image/jpeg', 0.8)
        .then(function (blob) {
          env.out_blob = blob
          return env
        })
    }

    Example: Rewrite scaling logic to use a min option

    import imageBlobReduce from 'image-blob-reduce'
    
    const reducer = imageBlobReduce()
    
    reducer._calculate_size = function (env) {
      const scale_factor = env.opts.min / Math.min(env.image.width, env.image.height)
    
      if (scale_factor > 1) scale_factor = 1
    
      env.transform_width = Math.max(Math.round(env.image.width * scale_factor), 1)
      env.transform_height = Math.max(Math.round(env.image.height * scale_factor), 1)
    
      return env
    }
  4. Use imageBlobReduce() to create a reducer instance

    master

    The imageBlobReduce() factory function creates a new reducer instance. You can also import the ImageBlobReduce class directly to instantiate it via new ImageBlobReduce([options]).

    Options:

    • pica: A pica instance. Providing this allows you to use different defaults or a shared web worker pool.
    import imageBlobReduce, { ImageBlobReduce } from 'image-blob-reduce'
    
    const reduce = imageBlobReduce()
    
    reduce instanceof ImageBlobReduce // true
  5. Downscale images with .toBlob()

    master

    Downscales an image so its width and height fit within the max pixel constraint (e.g., { max: 1000 } limits the longest side to 1000px). If the input is a JPEG, it applies orientation and reuses metadata with minimal changes.

    Returns: Promise<Blob>

    Options:

    • max: Max allowed width/height, in pixels.
    • pica .resize() options: quality, filter, unsharpAmount, unsharpRadius, unsharpThreshold, cancelToken.
    // Example usage
    const blob = await reduce.toBlob(in_blob, { max: 1000, quality: 0.8 });
  6. Downscale images with .toCanvas()

    master

    Identical to .toBlob(), but returns a HTMLCanvasElement instead of a Blob.

    Returns: Promise<HTMLCanvasElement>

    Options:

    • max: Max allowed width/height, in pixels.
    • pica .resize() options: quality, filter, unsharpAmount, unsharpRadius, unsharpThreshold, cancelToken.
  7. Extend the reducer with hooks and plugins

    master

    The reducer provides several methods to customize its pipeline:

    • .before(method_name, hook_fn): Injects a custom handler before the specified method.
    • .after(method_name, hook_fn): Injects a custom handler after the specified method.
    • .use(plugin_init, ...params): A sugar method to register external plugins. It calls plugin_init(this, ...params).
    • .setup(): Configures the instance before first use. By default, it installs built-in JPEG hooks. Use this to override pipeline methods or add custom plugins.
  8. Reference: Re-exported symbols

    master

    The following symbols are re-exported from image-blob-reduce:

    • imageBlobReduce: Default factory function.
    • ImageBlobReduce: Reducer constructor class.
    • image_traverse: JPEG traversal helpers.
    • pica: pica factory.
    • Pica: pica constructor.
    import imageBlobReduce, { ImageBlobReduce, image_traverse, pica, Pica } from 'image-blob-reduce'
  9. Extend the pipeline with before() and after() hooks

    master

    The ImageBlobReduce pipeline consists of several internal stages. You can intercept these stages using before(method_name, fn) or after(method_name, fn) to modify the environment (ImageBlobReduceEnv) during processing.

    Available Hook Methods:

    • _blob_to_image: When the Blob is converted to an HTMLImageElement.
    • _calculate_size: When the target dimensions are calculated.
    • _transform: When the actual resizing via Pica occurs.
    • _cleanup: When temporary resources (like Object URLs) are cleaned up.
    • _create_blob: When the final Blob is generated from the canvas.

    Each hook receives an env object and must return a Promise resolving to the updated env object.

    reducer.before('_calculate_size', async (env) => {
      console.log('Calculating size for:', env.blob.type);
      return env;
    });
    
    reducer.after('_transform', async (env) => {
      console.log('Transformation complete');
      return env;
    });
  10. Downscale a Blob to a new Blob with toBlob()

    master

    The toBlob method takes an input Blob and returns a Promise that resolves to a new, downscaled Blob. You can pass ImageBlobReduceResizeOptions to control the resizing behavior, specifically the max property which limits the longest dimension of the image.

    Options:

    • max: The maximum dimension (width or height) allowed for the output image. Defaults to Infinity (no downscaling).
    • Other options are passed directly to the underlying pica library.
    const blob = // ... your input blob
    const reducedBlob = await reducer.toBlob(blob, { max: 1000 });
  11. Downscale a Blob to a Canvas with toCanvas()

    master

    The toCanvas method takes an input Blob and returns a Promise that resolves to a PicaCanvas. This is useful if you want to render the downscaled image directly to the DOM without creating an intermediate Blob.

    const blob = // ... your input blob
    const canvas = await reducer.toCanvas(blob, { max: 800 });
    // Use the canvas in your application
    document.body.appendChild(canvas);