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:
JavaScript
x
9
1
from os import listdir
2
from PIL import Image
3
4
5
img = Image.open('https://furniload.com/furni/js_c16_lounger.png')
6
img.verify()
7
8
print('Bad file:' +img)
9
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.
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.]- 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.
JavaScript
1
20
20
1
from PIL import Image
2
import requests
3
from PIL import UnidentifiedImageError
4
5
url = 'https://furniload.com/furni/js_c16_lounger.png'
6
response = requests.get(url)
7
8
# download and save fiel from web
9
with open("sample_image.png", "wb") as file_object:
10
file_object.write(response.content)
11
12
# pass the local file to PIL
13
local_image = "sample_image.png"
14
try:
15
img = Image.open("sample_image.png")
16
img.verify()
17
# if file is not an image, catch error and display message
18
except UnidentifiedImageError:
19
print('Bad file:' + local_image)
20
OUTPUT :
JavaScript
1
2
1
Bad file:sample_image.png
2