JIMP Image Composite. Add watermark

Viewed 1087

Consider a scenario where I want to add watermark at different places to an image and generate individual copies of each of them.

The images are uploaded to AWS S3.

const AWS = require('aws-sdk');
const Jimp = require('jimp');

I am using AWS SDK to fetch those images as buffer

const dynamoS3Bucket = new AWS.S3();
let a = dynamoS3Bucket.getObject({ Bucket: 'bucket.name', Key: 'raw_uploads/Sample-image10-highres.jpg' }).promise();
let b = dynamoS3Bucket.getObject({ Bucket: 'bucket.name', Key: 'raw_uploads/Sample-image10-highres.jpg' }).promise();

Now, I am trying to add a watermark as where a is the image and b is the logo

Promise.all([a, b]).then(async resp => {
    let aa = watermark(30, resp[0].Body, resp[1].Body, 0, 1);
    let bb = watermark(30, resp[0].Body, resp[1].Body, 1, 0);

    return Promise.all([aa, bb]);
}).then(respArr => {
    return respArr[1].writeAsync('fileName2.jpg');
});

The watermark function goes as,

async function watermark(percent = 10, base, logo, x_axis = 0, y_axis = 0){
    percent = Math.ceil(percent);
    if(percent > 70) percent = 70;

    baseIMG = await Jimp.read(base);
    logoIMG = await Jimp.read(logo);

    logoIMG = await logoIMG.resize(Math.ceil(baseIMG.bitmap.width * percent / 100), Jimp.AUTO,  Jimp.RESIZE_BEZIER);

    x_axis = Math.ceil(x_axis);
    y_axis = Math.ceil(y_axis);
    if(x_axis !== 0) x_axis = x_axis/Math.abs(x_axis);
    if(y_axis !== 0) y_axis = y_axis/Math.abs(y_axis);

    console.log({percent, baseIMG, logoIMG, x_axis, y_axis });

    if(x_axis === 0) x_axis = Math.ceil((baseIMG.bitmap.width - logoIMG.bitmap.width)/2)
    else if (x_axis === 1) x_axis = Math.ceil(baseIMG.bitmap.width - logoIMG.bitmap.width)
    else x_axis = 0;

    if(y_axis === 0) y_axis = Math.ceil((baseIMG.bitmap.height - logoIMG.bitmap.height)/2)
    else if (y_axis === -1) y_axis = Math.ceil(baseIMG.bitmap.height - logoIMG.bitmap.height)
    else y_axis = 0;

    return baseIMG.composite(logoIMG, x_axis, y_axis, {
        mode: Jimp.BLEND_SOURCE_OVER,
        opacitySource: 0.4,
        opacityDest: 0.3
    });
}

Problem: The first processed image is perfectly fine be the second image has 2 watermarks and looks like below.

enter image description here

I have tried fixing the issue by processing one image at a time by nesting promises instead of Promise.all(). Is there any possible way to achieve this, or any explanation on why this might be happening?

0 Answers
Related