从文本生成条形码并将其转换为 base64

Generate barcode from text and convert it to base64

有人知道从字符串生成条形码图像(最好是代码 39)并将其转换为 base64 字符串的工具吗,可以这样使用:

var text = "11220"; // text to convert
var base64Str = textToBase64Barcode(text); // function to convert its input 
        // to an image formatted in a base64 string like : "data:image/jpeg;base64..."

?

使用JsBarcode这个函数会做你想做的事。

function textToBase64Barcode(text){
  var canvas = document.createElement("canvas");
  JsBarcode(canvas, text, {format: "CODE39"});
  return canvas.toDataURL("image/png");
}

如果你在node.js端需要这个功能,你可以试试下面

const bwipjs = require('bwip-js');

function textToBarCodeBase64 (text) {
    return new Promise((resolve, reject) => {
        bwipjs.toBuffer({
            bcid: 'code128',
            text: text,
            scale: 3,
            height: 10,
            includetext: true,
            textxalign: 'center'
        }, function(error, buffer) {
            if(error) {
                reject(error)
            } else {
                let gifBase64 = `data:image/gif;base64,${buffer.toString('base64')}`
                resolve(gifBase64)
            }
        })
    })
}

关于 bwip-js 请参阅 bwip-js 了解更多详情

从我的角度(前端)来看,备选方案是 bwipjs

const canvas = document.createElement('canvas');

    const dataURL = bwipjs
      .toCanvas(canvas, {
        bcid: 'upca', // Barcode type
        text: barcode,
        scale: 3, // 3x scaling factor
        height: 20, // Bar height, in millimeters,
        border: 5,
        includetext: true, // Show human-readable text
      })
      .toDataURL('image/png');