ApeironTsuka / node-webpmux

A mostly 1:1 re-implementation of webpmux as a Node module in pure Javascript. Only thing currently missing is a command-line version.
GNU Lesser General Public License v3.0
21 stars 8 forks source link

node-webpmux

A mostly-complete pure Javascript re-implementation of webpmux.
Can load "simple" lossy/lossless images as well as animations.

Install

npm install node-webpmux

Basic usage

const WebP = require('node-webpmux');
let img = new WebP.Image();
// Load an animation
await img.load('img.webp');
// Extract the (unprocessed) fourth frame
await img.demux('.', { frame: 3 });
// Replace the fourth frame with a new image from disk
await img.replaceFrame(3, 'different.webp'); // This preserves the existing frame settings
// Alternatively you can do
//   let frame = Image.generateFrame({ path: 'different.webp' });
//   img.frames[3] = frame;
// Which will completely replace the frame
// Save a new copy
await img.save({ path: 'newimg.webp' });
// Or alternatively, img.save() to save over the existing one

Exports

TYPE_LOSSY
TYPE_LOSSLESS
TYPE_EXTENDED
Constants for what type of image is loaded.

encodeResults: enum of values that set[Image/Frame]Data returns.

Image: The main class.

Class definition:

Class properties

.width (read-only)

The width of the loaded image.

.height (read-only)

The height of the loaded image.

.type (read-only)

The type of image from the TYPE_* constants table.

.hasAnim (read-only)

A boolean flag for easily checking if the image is an animation.

.hasAlpha (read-only)

A boolean flag for easily checking if the image has transparency in any way.

.frames (read-only)

Returns the array of frames, if any, or undefined.
Note that while the frames themselves are read/write, you shouldn't modify them.

.frameCount (read-only)

The number of frames in the image's animation, or 0 if it's not an animation.

.anim (read-only)

Direct access to the raw animation data (see below in the Layout for internal Image data section).

.iccp (read/write)

A Buffer containing the raw ICCP data stored in the image, or undefined if there isn't any.

.exif (read/write)

A Buffer containing the raw EXIF data stored in the image, or undefined if there isn't any.

.xmp (read/write)

A Buffer containing the raw XMP data stored in the image, or undefined if there isn't any.

Image member functions

async .initLib()

Calls Image.initLib(). This member function is no longer particularly useful and is kept for convenience.

async .load(source)

If source is a string, it tries to load that as a path to a WebP image.
If source is a buffer, it tries to load the contents of the buffer as a WebP image.

.convertToAnim()

Sets the image up for being an animation.

async .demux({ path = undefined, buffers = false, frame = -1, prefix = '#FNAME#', start = 0, end = 0 })

Dump the individual, unprocessed WebP frames to a directory.

async .replaceFrame(frameIndex, source)

Replaces a frame in the animation with another image from source. All other frame settings are preserved.

async .save(path = this.path, options)

Save the image to path. Options are described below in the Options for saving section.
If path is null, this will save the image to a Buffer and return it.

async .getImageData()

Get the raw RGBA pixel data for the image.
Returns a Buffer in the format [ r, g, b, a, r, g, b, a, ... ]. Values are range 0 - 255.
Use this for non-animations.
On error, this returns a Buffer full of 0s.

async .setImageData(buffer, { width = 0, height = 0, preset = 0, quality = 75, exact = false, lossless = 0, method = 4, advanced = undefined })

Encode buf as a new WebP using the provided settings and replace the image pixel data with it.
This preserves EXIF/ICCP/XMP if present.
Use this for non-animations.

If lossless is set above 0, then setting quality or method is discouraged as they will override settings in the lossless preset.
Return value can be checked against the values in WebP.encodeResults.

async .getFrameData(frameIndex)

Get the raw RGBA pixel data for a specific frame.
Use this for animations.

async .setFrameData(frameIndex, buffer, { width = 0, height = 0, preset = 0, quality = 75, exact = false, lossless = 0, method = 4, advanced = undefined })

Encode buffer as a new WebP using the provided settings and replace an existing frame's pixel data with it.
Use this for animations.

Static functions

async Image.initLib()

Initialize the internal library used for [get/set]ImageData and [get/set]FrameData described above.
There is no need to call this unless you plan to use one of those 4 functions.

Image.from(webp)

Use the contents of webp and return a new Image using them.
Mainly useful for passing Image into a Web Worker or NodeJS Worker and converting the passed object back into an Image instance.
Such an approach can be used to greatly speed up saving of animations or multiple images as libwebp is not multi-threaded beyond saving the alpha layer of lossy images.

async Image.save(path, options)

Save the options using Image.getEmptyImage().
Works the same as .save() otherwise.
Can be used to create an animation from scratch by passing frames in options.
  Example: Image.save('animation.webp', { frames: ... }) for saving to file   OR   Example: Image.save(null, { frames: ... }) for saving to Buffer

async Image.getEmptyImage(ext)

Returns a basic, lossy 1x1 black image with no alpha or metadata.
Useful if you need to create a WebP from scratch, such as when converting from PNG.
.setImageData() would be used to change the canvas size/contents.
Set ext to true to force the image to be an extended type, if desired. This is mainly for use internally.

async Image.generateFrame({ path = undefined, buffer = undefined, img = undefined, x = undefined, y = undefined, delay = undefined, blend = undefined, dispose = undefined })

Generates enough of an anmf structure to be placed in .frames.
Note that, at the moment, only static images are supported in this function.

Options for saving

These options affect both static images and animations

The options below are only used when saving an animation:

Information about the internal library

[get/set]ImageData and [get/set]FrameData are powered by Google's official libwebp library obtained from the GitHub mirror.
Commit 89c5b91 was the latest at the time of compilation.
This library was compiled with Emscripten with the command emcc -O3 -s WASM=1 -s MODULARIZE -s EXPORTED_RUNTIME_METHODS='[cwrap]' -s ALLOW_MEMORY_GROWTH=1 -s EXPORT_NAME=LibWebP -DHAVE_CONFIG_H -I libwebp binding.cpp libwebp/src/{dec,dsp,demux,enc,mux,utils}/*.c libwebp/sharpyuv/*.c --bind -o libwebp.js.
binding.cpp is a shim I wrote to bridge the needed parts together and can be found in the libwebp/ directory. libwebp.js, found in the root, is the Javascript interface to it.

At present, the only options for encoding are setting the lossless preset, quality, method, and exact flag.
If access to other options is desired (see upstream libwebp/src/webp/encode.h, struct WebPConfig for settings), leave a feature request and I'll add it.
The upstream command line tool cwebp can be used to play with the features and see what you find useful.

Layout for internal Image data

{
  path, // The path loaded.
  loaded, // Boolean flag for if this object has an image loaded.
  data: { // The loaded data.
    type, // The type of image from the constants table.
    vp8: { // The lossy format image. Only if .type is TYPE_LOSSY or TYPE_EXTENDED.
      raw, // The raw, compressed image data from the VP8 chunk.
      width, height // The width/height, extracted from the VP8 image data.
    },
    vp8l: { // The lossless format image. Only if .type is TYPE_LOSSLESS or TYPE_EXTENDED.
      raw, // The raw, compressed image data from the VP8L chunk.
      alpha, // A flag for if this image has alpha data, extracted from the VP8L image data.
      width, height // The width/height, extracted from the VP8L image data.
    },
    extended: { // Only if .type is TYPE_EXTENDED.
      raw, // The raw data for the VP8X chunk.
      hasICCP, // Flag for if there's an ICC profile chunk defined.
      hasAlpha, // Flag for if any image/frame defined has alpha data.
      hasEXIF, // Flag for if there's an EXIF chunk defined.
      hasXMP, // Flag for if there's an XMP chunk defined.
      hasAnim, // Flag for if this image has an animation defined.
      width, height // Width/height of the image.
    },
    anim: {
      raw, // A Buffer containing the raw data for the ANIM chunk. Mainly for internal use.
      bgColor, // The background color in [ r, g, b, a ] format.
      loops, // The loop count.
      frames: [ // Array of frames
        { // The frame object definition
          raw, // The raw data for the ANMF chunk. Mainly for internal use.
          type, // The type of image this frame is, from the constants table.
          x, y, // The frame's x, y position.
          width, height, // The frame's width and height.
          delay, // The duration of the frame.
          blend, dispose, // The frame's blend/dispose flags.
          // Additionally, one or more of the following.
          vp8, // The raw, compressed WebP data for a lossy image. If present, there will be no `vp8l`.
          vp8l, // The raw, compressed WebP data for a lossless image. If present, there will be no `vp8` or `alph`.
          alph // The raw, compressed WebP data for an alpha map. Might be present if the image is lossy.
        },
        ...
      ]
    },
    alph: {
      raw // The raw alpha map chunk. Only likely to be here if .vp8 is also defined and .type is TYPE_EXTENDED.
    },
    iccp: {
      raw // The raw ICCP chunk, if defined.
    },
    exif: {
      raw // The raw EXIF chunk, if defined.
    },
    xmp: {
      raw // The raw XMP chunk, if defined.
    }
  }
}

Breaking changes from 1.x

Image.muxAnim and .muxAnim were merged into Image.save and .save respectively.

.anim.backgroundColor renamed to .anim.bgColor for brevity and consisteny.
.anim.loopCount renamed to .anim.loop for consistency.
.anim.frameCount and .frameCount were removed. Should use .anim.frames.length and .frames.length respectively instead.
.demuxAnim() was renamed to .demux()

Breaking changes from 2.0.0 to 2.0.1

Image.generateFrame()'s duration input renamed to delay

Breaking changes from 2.x to 3.0.0

File and buffer codepaths have been merged.