v8.77.0

Add a watermark to the image

We can use the postProcessImageData hook on the createDefaultImageWriter function to add a watermark to the imageData before the output file is created.

<!DOCTYPE html>

<head>
    <link rel="stylesheet" href="./pintura.css" />
</head>

<img src="" alt="" />

<style>
    .pintura-editor {
        height: 600px;
    }
</style>

<div id="editor"></div>

<script type="module">
    import { appendDefaultEditor, processImage } from './pintura.js';

    const editor = appendDefaultEditor('#editor', {
        src: 'image.jpeg',
        imageWriter: {
            targetSize: {
                width: 512,
                height: 512,
                fit: 'contain',
            },
            postprocessImageData: (imageData) =>
                new Promise((resolve, reject) => {
                    // Create a canvas element to handle the imageData
                    const canvas = document.createElement('canvas');
                    canvas.width = imageData.width;
                    canvas.height = imageData.height;
                    const ctx = canvas.getContext('2d');
                    ctx.putImageData(imageData, 0, 0);

                    // Draw our watermark on top
                    const watermark = new Image();
                    watermark.onload = () => {
                        // how to draw the image to the canvas
                        ctx.globalCompositeOperation = 'screen';

                        // draw the watermark in the top right corner
                        ctx.drawImage(
                            watermark,

                            // the watermark x and y position
                            imageData.width - 100 - 20,
                            20,

                            // the watermark width and height
                            100,
                            40
                        );

                        // Get and return the modified imageData
                        resolve(
                            ctx.getImageData(
                                0,
                                0,
                                imageData.width,
                                imageData.height
                            )
                        );
                    };
                    watermark.onerror = reject;
                    watermark.crossOrigin = 'Anonymous';
                    watermark.src = './my-watermark.svg';
                }),
        },
    });

    editor.on('process', (imageState) => {
        document.querySelector('img').src = URL.createObjectURL(
            imageState.dest
        );
    });
</script>