Loading and saving GIFs

Browsers can load GIF images to the canvas but cannot output GIF images.

To work around this browser limiation we can use the postprocessImageBlob property on the createDefaultImageWriter function to convert images to different formats.

The third-party library gif.js can convert JPEGs and PNGs to GIFs, we'll use it in the postprocessImageBlob hook.

In the example below gif.js needs to be added using a script tag, see the gif.js documentation for more information.

import { openDefaultEditor } from './pintura.js';

// Open the default image editor in a modal
const editor = openDefaultEditor({
    src: './my-image.jpeg',
    imageWriter: {
        postprocessImageBlob: ({ blob }) =>
            new Promise((resolve) => {
                // Load the output blob as an image so we can load it with gif.js
                const image = new Image();
                image.onload = () => {
                    // The image has loaded, let's create a GIF
                    const gif = new GIF();
                    gif.addFrame(image);
                    gif.on('finished', (gifBlob) => {
                        // clean up URL to our output image
                        URL.revokeObjectURL(blob);

                        // return the GIF to the editor
                        resolve(gifBlob);
                    });
                    gif.render();
                };

                // Convert the blob to a URL so we can load it as an image
                image.src = URL.createObjectURL(blob);
            }),
    },
});

// Show resulting image preview
editor.on('process', ({ dest }) => {
    const preview = new Image();
    preview.src = URL.createObjectURL(dest);
    document.body.appendChild(preview);
});