Skip to content
Advertisement

I can’t check broken images from a url

I am trying from a basic code from python to be able to verify the images that are broken, but I do not know how to do it

this is the code i am using:

from os import listdir
from PIL import Image


img = Image.open('https://furniload.com/furni/js_c16_lounger.png') 
img.verify()
    
print('Bad file:' +img) 

Can someone help me!

Thank you very much!

Advertisement

Answer

There are a couple of things that needs to be done to verify if a file from web is an image or not.

  1. PIL.Image method accepts a file object or a string for local file, whereas you are trying to provide a web link. [You can download the file, save it locally and then open it.]
  2. You need to catch the exception, if there is any, and then display if the file is bad or not.

I have added the basic code below.

from PIL import Image
import requests
from PIL import UnidentifiedImageError

url = 'https://furniload.com/furni/js_c16_lounger.png'
response = requests.get(url)

# download and save fiel from web
with open("sample_image.png", "wb") as file_object:
  file_object.write(response.content)

# pass the local file to PIL
local_image = "sample_image.png"
try:
  img = Image.open("sample_image.png")
  img.verify()
# if file is not an image, catch error and display message  
except UnidentifiedImageError:
  print('Bad file:' + local_image) 

OUTPUT :

Bad file:sample_image.png
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement