以下代码抛出错误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?
UPDATE
Error with file: Object of type bytes is not JSON serializable
Error with file: single positional indexer is out-of-bounds
使用BytesIO
答案 0 :(得分:2)
这是使用ByteIO而不是StringIO的简短但完整的代码演示。我还添加了执行反向转换的功能。它可以在Python 2.6和3.6上正确运行。唯一的区别是在Python 3中,Base64输出是一个b
字符串。
from PIL import Image
from io import BytesIO
import base64
# Convert Image to Base64
def im_2_b64(image):
buff = BytesIO()
image.save(buff, format="JPEG")
img_str = base64.b64encode(buff.getvalue())
return img_str
# Convert Base64 to Image
def b64_2_img(data):
buff = BytesIO(base64.b64decode(data))
return Image.open(buff)
# Test
img = Image.new('RGB', (120, 90), 'red')
img.show()
img_b64 = im_2_b64(img)
print(img_b64)
new_img = b64_2_img(img_b64)
new_img.show()
Python 3输出
b'/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCABaAHgDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDi6KKK+ZP3EKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9k='