python - 从 Python2 升级到 Python3 时的字符串/字节问题

标签 python python-3.x qr-code python-imaging-library

我尝试以这种方式使用 Python 3 生成 QRCode 的 base64 img:

def gen_qrcode(data):
    import base64
    import io
    import qrcode

    qrc = qrcode.QRCode(version=1,
                        error_correction=qrcode.constants.ERROR_CORRECT_Q,
                        box_size=8,
                        border=4)
    qrc.add_data(data)
    qrc.make(fit=True)
    img = qrc.make_image()

    output = io.StringIO()
    img.save(output, 'PNG') # This line is now a problem with Python 3
    output.seek(0)
    output_s = output.read()
    b64 = base64.b64encode(output_s)
    img_tag = '<img src="data:image/png;base64,{0}">'.format(b64)

    return img_tag

它在 Python 2 上运行良好(唯一更改的代码是 StringIO 被 IO 替换)但现在我有一个错误:

TypeError at /qrcode
string argument expected, got 'bytes'
-> img.save(output, 'PNG')

有什么想法吗? 谢谢。

最佳答案

output = io.BytesIO

这将期望字节并产生字节以输入到 base64.b64encode。

要从结果输出中删除前导“b”,必须使用注释中提到的 .decode():

b64 = base64.b64encode(output_s).decode()

关于python - 从 Python2 升级到 Python3 时的字符串/字节问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26088946/

相关文章:

python - pandas 数据框中按日期对齐行

python-3.x - keras lstm 性能不佳

Python 将列表 reshape 为多维列表

javascript - 尝试扫描二维码然后调用 API

python - 如何先按键排序,然后按嵌套值排序

python - 让 Hello World 在 pymacs 中工作

python - 使用python从sqlite db读取unicode

unit-testing - 从 reduceByKey() 调用函数时单元测试期间的导入错误

ios - 尝试将变量从一个类移动到另一个类

java - Apache FOP 1.1 QRCodes 与 zxing