AttributeError: 'str' object has no attribute 'tostring'

给你一囗甜甜゛ 提交于 2019-12-13 05:05:28

问题


Trying to convert image to string....

import requests
image = requests.get(image_url).content
image.tostring()

I get the error:

AttributeError: 'str' object has no attribute 'tostring'

How do I turn this into something that Python understands as an image which I can then call tostring() on?


回答1:


The .content attribute of a response is already a string. Python string objects do not have a tostring() method.

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 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


来源:https://stackoverflow.com/questions/25341130/attributeerror-str-object-has-no-attribute-tostring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!