需求
最近想做一个小工具,大概要实现这样的效果:后端生成条形码后,不保存到服务器,直接返回给前端展示。
大概思路是,通过 python-barcode库 生成条码的字节流,生成字节流后直接编码成base64格式返回给前端,前端通过img标签展示base64格式的图片。
代码示例
后端代码
以flask为例,其他web框架实现的方法类似。
这里使用Code128格式的条码,可以去python-barcode官网看看,该工具还支持生成其他格式的条码。
@app.route('/barcode', methods=['POST'])
def bar_code():
    param_code = request.get_json()['barCode']
    buffer = BytesIO()
    Code128(param_code, writer=SVGWriter()).write(buffer)
    res = base64.b64encode(buffer.getvalue()).decode('utf-8')
    return {
        "code": 200,
        "message": "success",
        "data": res
    }前端代码
以vue为例
<template>
    <img :src="imgUrl" />
</template>
<script setup>
import { onMounted, ref, inject } from 'vue'
const axios = inject("$axios")
const imgUrl = ref(null)
const load_barcode = async () => {
    // 请求后台
    const param = {
        "barCode": "100000902922"
    }
    let res = await axios.post("http://127.0.0.1:5000/barcode", param);
    // 获取base64格式的图片
    const b4 = res.data.data
    // 绑定到img的src
    imgUrl.value = "data:image/svg+xml;base64," + b4
}
onMounted(() => {
    load_barcode()
})
</script>最后的效果

如有问题,欢迎指正。