python-3.ximagepngwebp

How to check if a .webp file is a gif or image in python using PIL?


I was trying to make a ".webp extractor script" in python where I'd loop through a pre-determined file directory searching for .webp's to then decide whether they were a .gif file type saved as a .webp or not so I could save the .webp as a .gif or if it wasn't a .gif as a .webp it would therefore be a image such as a .jpg/.png saved as a .webp so I could just save the .webp as a image.

However, detecting whether a .webp was storing a gif or image was a bit confusing, here was my code prior to checking :

import os
from PIL import Image

for entry in os.scandir(Directory):
    Searched += 1
    if entry.path.endswith(".webp") and entry.is_file():
        print("--------------")
        print("Found a : .webp")
        print(entry.path)

        IsAGif = False

        MediaFile = Image.open(entry.path)

Then I was stuck from there and had to try find some solutions. But I had to change my mindset and think, logically. And what I thought was that .gif have multiple image frames whereas a image such as a .png only has one. So if I could read the .webp file and find that out, I could distinguish between a image and .gif...


Solution

  • And eventually, I found how to read the frames in a image / .gif which was :

    import os
    from PIL import Image, ImageSequence
    
    MediaFile = Image.open(entry.path)
    for frame in ImageSequence.Iterator(MediaFile):
         #Rest of code here
    

    Hence, to find if a .webp is a .gif or image, I just need to read how many frames there are. If there is one frame, the .webp is a image, else if it is more than one frame it is a .gif because it's transitioning between the frames. Hence I present a function for this :

    from PIL import Image, ImageSequence
    
    def IsAGif(FilePath):
        try:
            MediaFile = Image.open(FilePath)
            Index = 0
            for Frame in ImageSequence.Iterator(MediaFile):
                Index += 1
            if Index > 1: #Must mean the the .webp is a gif because it has more than one frame
                return True
            else: #Must mean that the .webp has 1 frame which makes it a image
                return False
        except: #If the .webp can't be opened then it is most likely not a .gif or .webp
            return False