How to extract base64 extension without using lib imghdr

296 Views Asked by At

I have a view that works perfectly for receiving base64 images. My problem is that in some rare cases it doesn't recognize the sent jpg image. It looks like None.

Looking on the internet I saw that the problem is the lib imghdr. I tried to use OS lib to extract the extension and even use the lib pillow, but I couldn't.

Does anyone have any tips?

Here is an example of how I use imghdr:

    def get_file_extension(self, file_name, decoded_file):
        import imghdr

        extension = imghdr.what(file_name, decoded_file)
        if extension == "jpeg":
            extension = "jpg"

        return extension
1

There are 1 best solutions below

0
On BEST ANSWER

You can write a simple utility function to extract the extension

def base64_ext(b64str):
    # b64str format example: 'data:image/jpeg;base64, LzlqLzRBQ...'
    fmt, imgstr = b64str.split(';base64,') 
    ext = fmt.split('/')[-1]
    return ext