0

I am trying to download an image using PIL but its shows an UnidentifiedImageError

d = login_session.get("https://example.com/xyz.php")
d = Image.open(BytesIO(d.content))
d.save("xyz.png")

Here I need to log into a site first and then download an image, so for that, I used login_session to make a session

  File "C:/Users/dx4io/OneDrive/Desktop/test.py", line 21, in <module>
    captcha = Image.open(BytesIO(captcha.content))
  File "C:\Users\dx4io\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\Image.py", line 3024, in open
    "cannot identify image file %r" % (filename if filename else fp)
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x000001A5E1B5AEB8>
dx4iot
  • 53
  • 1
  • 8

1 Answers1

1

The problem is that the page you are trying to go to does not return an image. For example, a page which returns an image is https://www.google.com/favicon.ico, but google searching for image returns an html page: https://www.google.com/search?q=image.

To test we can try to get an image from a page which isn't an image.

from io import BytesIO
from PIL import Image
import requests

notanimage='https://www.google.com/search?q=image'
yesanimage="https://www.google.com/favicon.ico"

Now running this code works:

d = requests.get(yesanimage)
d = Image.open(BytesIO(d.content))
d.save("xyz.png")

but this gives an UnidentifiedImageError:

d = requests.get(notanimage)
d = Image.open(BytesIO(d.content))
d.save("xyz.png")

This code runs without errors:

from io import BytesIO
from PIL import Image
import requests
d = requests.get("https://defendtheweb.net/extras/playground/captcha/captcha1.php")
d = Image.open(BytesIO(d.content))
d.save("xyz.png")
Ukulele
  • 612
  • 2
  • 10