Last active
December 5, 2019 00:38
-
-
Save vmmartinezlona/cd42c303c611ca05ec7ff611f0f1762f to your computer and use it in GitHub Desktop.
Upload a watermark image with Jimp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const Jimp = require('jimp'); | |
const AWS = require('aws-sdk'); | |
AWS.config.update({ | |
region: '****', | |
endpoint: '****', | |
accessKeyId: '****', | |
secretAccessKey: '****' | |
}); | |
const s3 = new AWS.S3({ | |
region: '***', | |
endpoint: '***' | |
}); | |
const inputFileS3Url = '***'; | |
const waterMark = { | |
text: 'Watermark test text', | |
alignmentX: Jimp.HORIZONTAL_ALIGN_LEFT, | |
alignmentY: Jimp.VERTICAL_ALIGN_BOTTOM | |
} | |
// background image for the watermark | |
const watermarkBackground = '****'; | |
printWaterMark(waterMark); | |
async function printWaterMark(imageCaption) { | |
const image = await Jimp.read(inputFileUrl); | |
const background = await Jimp.read(watermarkBackground); | |
const imgWidth = image.bitmap.width; | |
const imgHeight = image.bitmap.height; | |
const font = await getFont(imgHeight); | |
var textLong = Jimp.measureText(font, imageCaption.text); | |
var backgroundHeight = imgHeight-(getBackgroundHeight(imgHeight)); | |
image.blit(background, 0, backgroundHeight, 0, 0, imgWidth, 0); | |
image.print(font, 10, getBackgroundHeight(imgHeight), imageCaption, textLong, imgHeight); | |
image.getBuffer(Jimp.AUTO, function(error, result){ | |
s3.putObject( | |
{ | |
Bucket: '****', | |
Key: '****', | |
Body: result, | |
ContentType: '****', | |
ACL: '****' | |
}, | |
function(err, data) { | |
if (err) { | |
console.log('Failed saving to S3', err); | |
} | |
}); | |
}); | |
} | |
async function getFont(imageHeight){ | |
var font; | |
var fontHeight = Math.floor(imageHeight / 10); | |
if(fontHeight <= 16){ | |
font = Jimp.FONT_SANS_8_WHITE; | |
} else if (fontHeight >= 16 && fontHeight <= 32) { | |
font = Jimp.FONT_SANS_16_WHITE; | |
} else if (fontHeight >= 32 && fontHeight <= 64) { | |
font = Jimp.FONT_SANS_32_WHITE; | |
} else if (fontHeight >= 64 && fontHeight <= 128) { | |
font = Jimp.FONT_SANS_64_WHITE; | |
} else if (fontHeight > 128) { | |
font = Jimp.FONT_SANS_128_WHITE; | |
} | |
return await Jimp.loadFont(font); | |
} | |
function getBackgroundHeight(imageHeight){ | |
var fontHeight = Math.floor(imageHeight / 10); | |
if(fontHeight <= 16){ | |
return 20; | |
} else if (fontHeight >= 16 && fontHeight <= 32){ | |
return 32; | |
} else if (fontHeight >= 32 && fontHeight <= 64){ | |
return 40; | |
} else if (fontHeight >= 64 && fontHeight <= 128){ | |
return 70; | |
} else if (fontHeight >= 64 && fontHeight > 128){ | |
return 130; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result image