以下代码抛出了一个错误:
Error with file: string argument expected, got 'bytes'
我还尝试使用BytesIO
,但它抛出了一个关于需要string
格式而不是bytes
的错误。非常令人困惑。def im_2_b64(image):
buffer = StringIO()
image.save(buffer, format="JPEG")
img_str = base64.b64encode(buffer.getvalue())
return img_str
我该如何使用python 2.7将图像转换为base64格式?
更新
Error with file: Object of type bytes is not JSON serializable
Error with file: single positional indexer is out-of-bounds
使用 BytesIO
StringIO()
更改为BytesIO()
,那段代码对我来说就可以正常工作。你确定你是在 Python 2 上运行它吗? :) 实际上,在 Python 3 中也可以正常工作。 - PM 2Ringbuffer
不是一个很好的变量名,因为它会与内置的buffer
类型发生冲突。 - PM 2Ring