Need help checking the validity of an image file in Python

0 votes

Hi all, with regard to the above question I am making use of the Python Image Library (PIL).

Check out this code:

from PIL import Image
try:
    im=Image.open(filename)
    # exec some code
except IOError:
    # filename not an image file

I am already aware that this is more than enough for multiple file types but my question is that if I have file types such as PSD, SVG or even XCF then these are not being detected for some reason.

PSD files actually throw the OverflowError exception for this and all I want to know is if there is a way which involves me including these files as well?

All help appreciated, cheers!

Jan 18 in Python by Anirudh
• 2,070 points
49 views

1 answer to this question.

0 votes

I went through the Python documentation and I found that the built-in imghdr module can be used for this. 

This is what I found from the official docs:
"The imghdr module determines the type of image contained in a file or byte stream."

And check out the code to see it in action:

>>> import imghdr
>>> imghdr.what('/tmp/bass')
'gif'

So, in my opinion, using a module is really much recommended instead of implementing the same functionality again.

Hope this helped!

answered Jan 18 by Nymeria
• 3,520 points

Related Questions In Python

+2 votes
3 answers

How can I play an audio file in the background using Python?

down voteacceptedFor windows: you could use  winsound.SND_ASYNC to play them ...READ MORE

answered Apr 3, 2018 in Python by charlie_brown
• 7,720 points
2,506 views
+1 vote
4 answers

Count the frequency of an item in a python list

To count the number of appearances: from collections ...READ MORE

answered Oct 18, 2018 in Python by tinitales
2,200 views
0 votes
1 answer

How can I find out the index of an element from row and column in Python?

You probably want to use np.ravel_multi_index: [code] import numpy ...READ MORE

answered Apr 16, 2018 in Python by charlie_brown
• 7,720 points
113 views
0 votes
1 answer

Is arr.__len__() the preferred way to get the length of an array in Python?

my_list = [1,2,3,4,5,6,7] len(my_list) # 7 The same works for ...READ MORE

answered Oct 8, 2018 in Python by SDeb
• 13,210 points
85 views
0 votes
1 answer
0 votes
1 answer

Need help with making use of Pluck in Python

Hi, good question. Easy solution to be ...READ MORE

answered Jan 24 in Python by Nymeria
• 3,520 points
157 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Need help extracting a schema to make use for an avro file in Python

Hi, nice question. So what I daily use ...READ MORE

answered Jan 10 in Python by Nymeria
• 3,520 points
679 views