how to identify webp image type with python

Question:

I want to identify the type of a Image to tell whether it’s a webp format or not, but I can’t just using file command because the image is stored in memory as binary which was download from the internet. so far I can’t find any method to do this in the PIL lib or imghdr lib

here is what I wan’t to do:

from PIL import Image
import imghdr

image_type = imghdr.what("test.webp")

if not image_type:
    print "err"
else:
    print image_type

# if the image is **webp** then I will convert it to 
# "jpeg", else I won't bother to do the converting job 
# because rerendering a image with JPG will cause information loss.

im = Image.open("test.webp").convert("RGB")
im.save("test.jpg","jpeg")

And when this "test.webp" is actually a webp image, var image_type is None which indict that the imghdr lib don’t know a webp type, so is there any way that I can tell it’s a webp image for sure with python?


For the record, I am using python 2.7


Asked By: armnotstrong

||

Answers:

The imghdr module doesn’t yet support webp image detection; it is to be added to Python 3.5.

Adding it in on older Python versions is easy enough:

import imghdr

try:
    imghdr.test_webp
except AttributeError:
    # add in webp test, see http://bugs.python.org/issue20197
    def test_webp(h, f):
        if h.startswith(b'RIFF') and h[8:12] == b'WEBP':
            return 'webp'

    imghdr.tests.append(test_webp)
Answered By: Martijn Pieters

The imghdr will be Deprecated.
https://docs.python.org/3/library/imghdr.html

Deprecated since version 3.11, will be removed in version 3.13: The imghdr module is deprecated (see PEP 594 for details and alternatives).

You can use PIL

>>> from PIL import Image
>>> img = Image.open('/tmp/imgc7e4913dbbde92e4256e89d702fc06af.jpg')
>>> img.format
'PNG'
>>> img = Image.open('/tmp/img29ba9e376d78288369b68702549d2b22.jpg')
>>> img.format
'WEBP'
Answered By: nameldk