我目前正在使用 python3,我的项目需要验证码生成。我的目标是生成验证码,然后将其作为 base64 返回,以便可以将其以 JSON 格式提供给客户端。
但是我无法将其转换为 base64 字符串:
captcha=image.generate(captchatext)
assert isinstance(captcha, BytesIO)
captcha=base64.b64encode(captcha)
返回错误:
captcha=base64.b64encode(captcha)
File "/usr/lib/python3.6/base64.py", line 58, in b64encode
encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not '_io.BytesIO'
我不完全确定为什么?有人可以帮我理解为什么它不会转换吗?
感谢您的帮助:)
最佳答案
将 BytesIO
对象转换为 bytes
类型:
captcha = base64.b64encode(image.generate(captchatext).getvalue())
这些类型不可互换,BytesIO
是一个类似文件的对象,bytes
只是存储不可变的值,如 str
关于python - 无法将验证码对象转换为 base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45056894/