1 function hex2rgba (hex) {
2 if (typeof hex === 'number') {
6 if (typeof hex !== 'string') {
7 throw new Error('Color should be defined as hex string')
10 var hexCode = hex.slice().replace('#', '').split('')
11 if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) {
12 throw new Error('Invalid hex color: ' + hex)
15 // Convert from short to long form (fff -> ffffff)
16 if (hexCode.length === 3 || hexCode.length === 4) {
17 hexCode = Array.prototype.concat.apply([], hexCode.map(function (c) {
22 // Add default alpha value
23 if (hexCode.length === 6) hexCode.push('F', 'F')
25 var hexValue = parseInt(hexCode.join(''), 16)
28 r: (hexValue >> 24) & 255,
29 g: (hexValue >> 16) & 255,
30 b: (hexValue >> 8) & 255,
32 hex: '#' + hexCode.slice(0, 6).join('')
36 exports.getOptions = function getOptions (options) {
37 if (!options) options = {}
38 if (!options.color) options.color = {}
40 var margin = typeof options.margin === 'undefined' ||
41 options.margin === null ||
42 options.margin < 0 ? 4 : options.margin
44 var width = options.width && options.width >= 21 ? options.width : undefined
45 var scale = options.scale || 4
49 scale: width ? 4 : scale,
52 dark: hex2rgba(options.color.dark || '#000000ff'),
53 light: hex2rgba(options.color.light || '#ffffffff')
56 rendererOpts: options.rendererOpts || {}
60 exports.getScale = function getScale (qrSize, opts) {
61 return opts.width && opts.width >= qrSize + opts.margin * 2
62 ? opts.width / (qrSize + opts.margin * 2)
66 exports.getImageWidth = function getImageWidth (qrSize, opts) {
67 var scale = exports.getScale(qrSize, opts)
68 return Math.floor((qrSize + opts.margin * 2) * scale)
71 exports.qrToImageData = function qrToImageData (imgData, qr, opts) {
72 var size = qr.modules.size
73 var data = qr.modules.data
74 var scale = exports.getScale(size, opts)
75 var symbolSize = Math.floor((size + opts.margin * 2) * scale)
76 var scaledMargin = opts.margin * scale
77 var palette = [opts.color.light, opts.color.dark]
79 for (var i = 0; i < symbolSize; i++) {
80 for (var j = 0; j < symbolSize; j++) {
81 var posDst = (i * symbolSize + j) * 4
82 var pxColor = opts.color.light
84 if (i >= scaledMargin && j >= scaledMargin &&
85 i < symbolSize - scaledMargin && j < symbolSize - scaledMargin) {
86 var iSrc = Math.floor((i - scaledMargin) / scale)
87 var jSrc = Math.floor((j - scaledMargin) / scale)
88 pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0]
91 imgData[posDst++] = pxColor.r
92 imgData[posDst++] = pxColor.g
93 imgData[posDst++] = pxColor.b
94 imgData[posDst] = pxColor.a