Skip to content

Instantly share code, notes, and snippets.

@Fensterbank
Created April 30, 2021 08:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fensterbank/59ec5becdf10de39c79d5fec41b90131 to your computer and use it in GitHub Desktop.
Save Fensterbank/59ec5becdf10de39c79d5fec41b90131 to your computer and use it in GitHub Desktop.
Generate qr code with company logo in the middle
const QRCode = require('qrcode');
const sharp = require('sharp');
const { v4: uuidv4 } = require('uuid');
/* entity is the object containing the company logo, url is the url the QR code points to */
const entity = {
logo: { url: '...' }
}
const url = 'https://company.tld'
// if no logo is available, we only create the QR code
if (!entity.logo) {
const dataURL = await QRCode.toDataURL(
url,
{
errorCorrectionLevel: 'M', type: 'image/png', width: 600, margin: false, color: {
dark: "#034aad",
light: "#FFF"
}
},
);
return {
'src': dataURL
};
}
// if we have a company logo, we composite it
const filePath = `./.cache/qr/${uuidv4()}.png`;
await QRCode.toFile(
filePath,
url,
{
errorCorrectionLevel: 'H', type: 'image/png', width: 600, margin: false, color: {
dark: "#034aad",
light: "#FFF"
}
},
);
const logoSource = sharp(`./public/${entity.logo.url}`);
const logo = await logoSource
.metadata()
.then((metadata) => {
return logoSource
.resize({
width: metadata.width > metadata.height ? 220 : null,
height: metadata.width > metadata.height ? null : 220,
fit: 'contain',
background: { r: 255, g: 255, b: 255 },
})
.extend({
top: 10,
bottom: 10,
left: 10,
right: 10,
background: { r: 255, g: 255, b: 255 }
})
.sharpen()
.png()
.toBuffer()
})
const oBuffer = await sharp(filePath)
.composite([{ input: logo, gravity: 'centre' }])
.png()
.toBuffer();
return {
'src': `data:image/png;base64,${oBuffer.toString('base64')}`,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment