cannot identify image file %r” % (filename if filename else fp)

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:Usersdx4ioAppDataLocalProgramsPythonPython37libsite-packagesPILImage.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>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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")


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x