Created
April 30, 2021 08:00
-
-
Save Fensterbank/59ec5becdf10de39c79d5fec41b90131 to your computer and use it in GitHub Desktop.
Generate qr code with company logo in the middle
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
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