Search code examples
javascriptaxioswatermark

Adding a watermark to a image before uploading with watermarkjs


I'm trying to add a watermark to a image with watermark.js before it get uploaded but, I can't quite figure out how to do it.

With the code i got underneath the upload part of the uploadFile function is working but, the image data gets lost within the watermark script somehow and the uploaded image on AWS S3 is just a small transparent square.

I've also added my function to preview the image, and this is working fine and displays the image with the watermark as it is supposed to.

So why is one of the functions working while the other have problems, what am I doing wrong in the uploadFile function?

const uploadFile = file => {
    axios.get(`/api/imageUpload/${file.type}`)
        .then(uploadConfig => {
            watermark([file, '../static/images/watermark_white.png'])
                .image(watermark.image.lowerRight())
                .then(img => {
                    axios.put(uploadConfig.data.url, img, {
                        headers: {
                            "Content-Type": file.type
                        },
                    }).then(() => {
                        props.onUpload(uploadConfig.data.key);
                    });
                });
        });
};

const previewFile = file => {
    if (!isImage(file)) {
        return;
    }

    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onloadend = () => {
        let img = document.createElement("img");
        img.src = reader.result;

        watermark([img, '../static/images/watermark_white.png'])
            .image(watermark.image.lowerRight())
            .then(function (img) {
                document.getElementById("gallery").appendChild(img);
            });
    };
};

Solution

  • Turns out I only had to change .image(watermark.image.lowerRight()) to .blob(watermark.image.lowerRight()) and everything works.