Decode Animated WebP using Javascript (React / NextJS)

444 Views Asked by At

I'm trying to decode animated WebP images. I'd like to extract the frames composing the animation as well as the delay for each frame.

Any idea of how to deal with decoding animated WebP images using JavaScript in a React / NextJS environment?

I've found node-webpmux (https://github.com/ApeironTsuka/node-webpmux), which is webpmux (https://developers.google.com/speed/webp/docs/webpmux?hl=es-419) for JavaScript. However, it's incompatible as it first tries to use the FS and crashes on Browsers, being incompatible with React / NextJS.

1

There are 1 best solutions below

2
JOSE CARLOS RODRIGUEZ BENITEZ On

I'm currently working with the framework, I'm seeing some issues with my frames for animates webP, but works fine!

I can share my code in NodeJS:

const WebpImage = require('node-webpmux').Image;
...
    const webPImage = await new WebpImage();
await webPImage.load(file);

if (webPImage.hasAnim) {
  const maxFrames = this.isReduceQuality() ? 1 : 3;

  if (webPImage.frames !== undefined && webPImage.frames.length > 1) {
    /**
     * Available frames for webp image.
     */
    const frames = [...webPImage.frames];

    /**
     * Evaluate to reduce the number of frames for the image.
     */
    const reduce = Math.round(webPImage.frames.length / maxFrames);

    /**
     * Cleaning frames for webp image.
     */
    webPImage.frames.splice(0, webPImage.frames.length);

    /**
     * Pushing webp image frames.
     */
    frames.forEach((frame, index) => {
      if (index % reduce === 0) {
        frame.delay = 300;
        webPImage.frames.push(frame);
      }
    });
  }

  return sharp(await webPImage.save(null), options);