AttributeError: 'str' object has no attribute 'tostring'
Question: 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?


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

