简体   繁体   English

从Python2升级到Python3时出现字符串/字节

[英]String / Bytes issue when upgrading from Python2 to Python3

I try to generate base64 img of QRCode using Python 3 this way: 我尝试使用Python 3以这种方式生成base64 img的QRCode:

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

It worked well with Python 2 (the only changed code is StringIO replaced by IO) but now I have an error: 它适用于Python 2(唯一更改的代码是由IO替换的StringIO)但现在我有一个错误:

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

Any idea? 任何的想法? Thanks. 谢谢。

output = io.BytesIO

This will expect bytes and produce bytes for input to base64.b64encode. 这将期望字节并产生输入到base64.b64encode的字节。

To remove the leading "b" from the resulting output .decode() has to be used as mentioned in the comments: 要从结果输出中删除前导“b”,必须按照注释中的说明使用.decode()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM