python - StringIO 初始值必须是 str,而不是 Bytes

标签 python python-3.x stringio

好的,我有这个代码:

from PIL import Image
import os, sys
import requests
from io import StringIO

url = "https://cdn.discordapp.com/avatars/247096918923149313/34a66572b9339acdaa1dedbcb63bc90a.png?size=256"
response = requests.get(url)
pp = Image.open(StringIO(response.content))
pp.save("image1.png")

pp = Image.open("image2c.png").convert("LA")
pp.save("image2c.png")

background = Image.open("image1.png").convert("RGBA")
foreground = Image.open("image2c.png").convert("RGBA")
foreground = foreground.resize((256, 256), Image.BILINEAR)
background.paste(foreground, (125, 325), foreground)
background.show()

这将返回错误:TypeError:initial_value 必须是 str 或 None,而不是 bytes

我看不出我错在哪里。有人可以帮忙吗?

最佳答案

response 是二进制数据(bytes),Image 也需要一些二进制数据。

所以:

pp = Image.open(StringIO(response.content))

在中间注入(inject)一个基于文本的IO对象:无法将字节转换为文本(下一个问题是:无法将文本数据读取到图像中)

修复:

from io import BytesIO
pp = Image.open(BytesIO(response.content))

编辑:更好的是,使用 Image.open(response.raw) 就像这里回答的那样:How to download image using requests

关于python - StringIO 初始值必须是 str,而不是 Bytes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44888689/

相关文章:

python-3.x - 在 windows xp 中运行由 python 3.5 制作的独立 exe

python-3.x - StringIO 示例不起作用

image - 如何使用 opencv python 库从内存缓冲区 (StringIO) 或 url 中读取图像

python - 更改原始对象时更改的对象列表

python - 即使失败也让 pip 安装模块

python - Cython 发出 'unnecessary' 警告

python flask : Download a file generated on the fly AND print a response

python - 在 python 中使用 Arcpy 具有两个 for 循环的非常慢的函数

Python CSV 插入最后换行符 - 我怎样才能避免它?

python-3.x - python中的静默错误处理?