Attributeerror: 'str' Object Has No Attribute 'tostring'
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 'tos
Solution 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
Post a Comment for "Attributeerror: 'str' Object Has No Attribute 'tostring'"