AttributeError:'str'对象没有属性'tostring' [英] AttributeError: 'str' object has no attribute 'tostring'
问题描述
试图将图像转换为字符串....
Trying to convert image to string....
import requests
image = requests.get(image_url).content
image.tostring()
我得到了错误:
AttributeError:"str"对象没有属性"tostring"
AttributeError: 'str' object has no attribute 'tostring'
如何将其转换为Python理解为图像,然后可以调用tostring()?
How do I turn this into something that Python understands as an image which I can then call tostring() on?
推荐答案
响应的.content
属性已经是字符串. Python字符串对象没有tostring()
方法.
The .content
attribute of a response is already a string. Python string objects do not have a tostring()
method.
枕头/PIL不在这里发挥作用; requests
库在加载图像URL时不返回Python图像库对象.如果希望有一个Image
对象,则需要从加载的数据中创建该对象:
Pillow / PIL in not coming into play here; the requests
library does not return a Python Image Library object when loading an image URL. If you expected to have an Image
object, you'll need to create that from the loaded data:
from PIL import Image
from io import BytesIO
import requests
image_data = BytesIO(requests.get(image_url).content)
image_obj = Image.open(image_data)
image_obj
然后是一个PIL Image
实例,现在您可以使用Image.tostring()
将其转换为原始图像数据:
image_obj
then is a PIL Image
instance, and now you can convert that to raw image data with Image.tostring()
:
>>> from PIL import Image
>>> from io import BytesIO
>>> import requests
>>> image_url = 'https://www.gravatar.com/avatar/24780fb6df85a943c7aea0402c843737?s=128'
>>> image_data = BytesIO(requests.get(image_url).content)
>>> image_obj = Image.open(image_data)
>>> raw_image_data = image_obj.tostring()
>>> len(raw_image_data)
49152
>>> image_obj.size
(128, 128)
>>> 128 * 128 * 3
49152
这篇关于AttributeError:'str'对象没有属性'tostring'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!