UNPKG

codify-node

Version:

Generates 1D, 2D, and composite barcodes in png, svg, or eps formats.

72 lines 2.18 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const pngjs_1 = require("pngjs"); function blobToBase64(png) { const chunks = []; return new Promise((resolve) => { png.pack(); png.on('data', (c) => chunks.push(c)); png.on('end', () => { const result = Buffer.concat(chunks); resolve('data:image/png;base64,' + result.toString('base64')); }); }); } function getBuffer(png) { return pngjs_1.PNG.sync.write(png); } function getRgbaColor(hex = '000000FF') { const colors = [ ...hex.match(/^([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i) ?? [] ]; const alpha = parseInt(colors[4], 16); if (colors.length >= 3) { return { red: parseInt(colors[1], 16), green: parseInt(colors[2], 16), blue: parseInt(colors[3], 16), alpha: !isNaN(alpha) ? alpha : 255 }; } return { red: 0, green: 0, blue: 0, alpha: 255 }; } function isEqualColor(a, b) { return a.red === b.red && a.green === b.green && a.blue === b.blue; } function render(bitmap, width, height, backgroundColor, foregroundColor) { const png = new pngjs_1.PNG({ width, height }); const backgroundColorRgba = getRgbaColor(backgroundColor); const foregroundColorRgba = getRgbaColor(foregroundColor); let i = 0; for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const color = { red: bitmap[i], green: bitmap[i + 1], blue: bitmap[i + 2] }; const rgba = isEqualColor(color, backgroundColorRgba) ? backgroundColorRgba : foregroundColorRgba; const pos = (png.width * y + x) << 2; png.data[pos] = rgba.red; png.data[pos + 1] = rgba.green; png.data[pos + 2] = rgba.blue; png.data[pos + 3] = rgba.alpha || 0; i += 3; } } return png; } exports.default = { blobToBase64, getBuffer, getRgbaColor, render }; //# sourceMappingURL=png.js.map