A mostly-complete pure Javascript re-implementation of webpmux.
Can load "simple" lossy/lossless images as well as animations.
npm install node-webpmux
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
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.
.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.
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.
path
: The directory to dump the frames to, if desired.buffers
: Return the frames as an array of Buffers instead of dumping to a path.prefix
: What to prefix the frame names with. Default is the file name of the original image (without .webp).
Format is \<prefix>_\<frame number>.webp.frame
: What frame to dump. Defaults to -1, which has it dump all available frames. Overrides start
/end
.start
: The first frame to dump. Defaults to the first frame.end
: The last frame to dump. Defaults to the last frame.async .replaceFrame(frameIndex, source)
Replaces a frame in the animation with another image from source
. All other frame settings are preserved.
frameIndex
: Which frame to replace. Frame indexes are 0-based.source
: If this is a string, the frame is loaded from disk. If this is a Buffer, the frame is loaded from there.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.
buffer
: A Buffer object with the raw pixels in RGBA order.width
/height
buf
has different dimensions than the original image.preset
: What image preset to use, if any.quality
: What quality to set.exact
: Preserve data in transparent pixels.false
, which means transparent pixels may be modified to help with compression.lossless
: Save the data as a lossy/lossless image.method
: Compression method to use.advanced
: Access to more advanced encoding settings offered by libwebpimageHint
: Hint for what type of image it is (only used for lossless encoding for now, according to libwebp spec).targetSize
: Specifies the desired target size in bytes.method
parameter.targetPSNR
: Specifies the minimum distortion to try to achieve.targetSize
parameter.segments
: Maximum number of segments to use.snsStrength
: Spacial Noise Shaping.filterStrength
filterSharpness
filterType
filterStrength
> 0 or autoFilter
> 0.autoFilter
: Auto-adjust the filter's strength.alphaCompression
: Algorithm for encoding the alpha plane.alphaFiltering
: Predictive filtering method for alpha place.alphaQuality
pass
: Number of entropy-analysis passes.showCompressed
: Export the compressed picture back.preprocessing
: Preprocessing filter.partitions
: log2(number of token partitions).partitionLimit
: Quality degredation allowed to fit the 512k limit on prediction modes coding.emulateJpegSize
: Compression parameters are remapped to better mat the expected output size from JPEG compression.threadLevel
: Try to use multi-threaded encoding.lowMemory
: Reduce memory usage but increase CPU use.nearLossless
: Near lossless encoding.useDeltaPalette
: Reserved for future lossless feature.useSharpYUV
: Use sharp (and slow) RGB->YUV conversion.qMin
: Minimum permissible quality factor.qMax
: Maximum permissible quality factor.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.
frameIndex
: Which frame to get. Frame indexes are 0-based..getImageData()
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.
frameIndex
: Which frame to get. Frame indexes are 0-based..setImageData()
.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.
path
/buffer
/img
Only one of these can be present.
path
will load image data from file.
buffer
will load from the buffer.
img
will use an existing Image instance.x
/y
/delay
/blend
/dispose
Explicitly set these properties. See the Options for saving section for what these do.exif
/iccp
/xmp
true
to save the existing ones, or pass a Buffer to replace them.width
/height
: Width/height of the image.bgColor
: The background color of the animation.loops
: Number of times the animation loops.x
/y
/delay
/blend
/dispose
: Changes the default frame x/y position where a frame omits it (see below).x
/y
defaults to 0.delay
defaults to 100.blend
defaults to true
.dispose
defaults to false
.frames
: An array of objects defining each frame of the animation with the following properties.x
/y
: x, y offset to place the frame within the animation.delay
: Length of this frame in miliseconds.blend
: Boolean flag for whether or not to use alpha blending when drawing the frame.true
(defined above).dispose
: Boolean flag to control frame disposal method.true
causes the background color to be drawn under the frame.false
draws the new frame directly.false
(defined above).[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.
{
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.
}
}
}
Image.muxAnim and .muxAnim were merged into Image.save and .save respectively.
Image.muxAnim({ path, frames, width, height, bgColor, loops, delay, x, y, blend, dispose, exif, iccp, xmp })
Image.save(path, undefined, { frames, width, height, bgColor, loops, delay, x, y, blend, dispose, exif, iccp, xmp })
.muxAnim({ path, width, height, bgColor, loops, delay, x, y, blend, dispose, exif, iccp, xmp })
.save(path, { width, height, bgColor, loops, delay, x, y, blend, dispose, exif, iccp, xmp })
.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()
Image.generateFrame()'s duration
input renamed to delay
File and buffer codepaths have been merged.
.loadBuffer(buffer)
.load(buffer)
Image.loadBuffer(buffer)
Image.load(buffer)
.saveBuffer(settings)
.save(null, settings)
Image.saveBuffer(settings)
Image.save(null, settings)
null
here. This is because the default behavior of .save() is still saving to the path it was loaded from.
.demuxToBuffers({ setting, setting, ... })
.demux({ buffers: true, setting, setting, ... })
.demux(path, settings)
.demux({ path, setting, setting, ... })
.replaceFrameBuffer(frame, buffer)
.replaceFrame(frame, buffer)