Sunday, February 9, 2020

Mike Driscoll: How to Check if a File is a Valid Image with Python

Python has many modules in its standard library. One that is often overlooked is imghdr which lets you identify what image type that is contained in a file, byte stream or path-like object.

The imghdr can recognize the following image types:

  • rgb
  • gif
  • pbm
  • pgm
  • ppm
  • tiff
  • rast
  • xbm
  • jpeg / jpg
  • bmp
  • png
  • webp
  • exr

Here is how you would use it imghdr to detect the image type of a file:

>>> import imghdr
>>> path = 'python.jpg'
>>> imghdr.what(path)
'jpeg'
>>> path = 'python.png'
>>> imghdr.what(path)
'png'

All you need to do is pass a path to imghdr.what(path) and it will tell you what it thinks the image type is.

An alternative method to use would be to use the Pillow package which you can install with pip if you don’t already have it.

Here is how you can use Pillow:

>>> from PIL import Image
>>> img = Image.open('/home/mdriscoll/Pictures/all_python.jpg')
>>> img.format
'JPEG'

This method is almost as easy as using imghdr. In this case, you need to create an Image object and then call its format attribute. Pillow supports more image types than imghdr, but the documentation doesn’t really say if the format attribute will work for all those image types.

Anyway, I hope this helps you in identifying the image type of your files.

The post How to Check if a File is a Valid Image with Python appeared first on The Mouse Vs. The Python.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...