All files / src/render data-url-gif.render.js

100% Statements 50/50
100% Branches 12/12
100% Functions 2/2
100% Lines 50/50

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 511x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3364x 1764x 1764x 1764x 3364x 1600x 1600x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 58x 3364x 3364x 58x 1x 1x 1x 1x 1x 1x  
import { gifImage } from './gif-image.render.js'
import { ByteArrayOutputStream } from '../utils/bite-array-output-stream.js'
import { bytesToBase64 } from '../utils/text-decode-encode.util.js'
 
/**
 *
 * @param {object} opts - function parameters
 * @param {number} [opts.cellSize] - cell size in pixels, defaults to 2
 * @param {number} [opts.margin] - margin in pixels, defaults to {@link cellSize} * 4
 * @param {import('../qr-code.js').QrCode} opts.qrcode - QR Code data
 * @returns {string} data url of qr code image
 */
export function createDataURL ({ cellSize = 2, margin, qrcode }) {
  margin ??= cellSize * 4
 
  const size = qrcode.moduleCount * cellSize + margin * 2
  const min = margin
  const max = size - margin
 
  return createDataURLAux(size, size, function (x, y) {
    if (min <= x && x < max && min <= y && y < max) {
      const c = Math.floor((x - min) / cellSize)
      const r = Math.floor((y - min) / cellSize)
      return qrcode.isDark(r, c) ? 0 : 1
    } else {
      return 1
    }
  })
};
 
/**
 *
 * @param {number} width - image width
 * @param {number} height - image height
 * @param {(x: number, y:number) => number} getPixel - get pixel function
 * @returns {string} data url of qr code image
 */
function createDataURLAux (width, height, getPixel) {
  const gif = gifImage(width, height)
  for (let y = 0; y < height; y += 1) {
    for (let x = 0; x < width; x += 1) {
      gif.setPixel(x, y, getPixel(x, y))
    }
  }
 
  const b = new ByteArrayOutputStream()
  gif.write(b)
  const base64 = bytesToBase64(b.toByteArray())
  return 'data:image/gif;base64,' + base64
};