Search code examples
pythonimagepython-imaging-librarywebp

how to identify webp image type with python


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



Solution

  • 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)