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

20

有没有工具可以从字符串生成条形码图像(最好是Code 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..."

?


2
这个库可能会很有用;https://github.com/lindell/JsBarcode - Ron Sims II
有条形码字体,也可以使用适当的CSS在div或span中构建图像。 - RobG
3个回答

45

使用JsBarcode,此函数将实现您的需求。

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

你刚刚救了我的一天!:) 非常感谢! - Naween Niroshan
Stack Overflow需要像您这样的人才。 - Gabriel Lam

3
如果您需要在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了解更多细节。


2

从我的角度来看(前端),另一种选择是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');

在JS/TS中如何使用它?当运行yarn unit-test时,我遇到一个错误:类型“typeof BwipJs”上不存在属性'toCanvas'。 - Sardar Faisal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接