1

Hello I'm trying to convert a base64 string to a image file, thats easy. Here is my code.

with open(os.path.join('avatars', avatar_filename), 'wb') as avatar_file:
    avatar_file.write(base64.decodebytes(avatar_b64))

But the problem is that the string is sent by a client so, how can i know if the base64 string corresponds to a image file?

rayitopy
  • 111
  • 2
  • 9
  • You can try the code in this answer. https://stackoverflow.com/a/34116876/270349 – aalku Sep 13 '17 at 07:50
  • Yes, that's the same that i have, but i can't know if the base64 string corresponds to a image file. – rayitopy Sep 13 '17 at 07:55
  • 2
    Possible duplicate of [How to check if a file is a valid image file?](https://stackoverflow.com/questions/889333/how-to-check-if-a-file-is-a-valid-image-file) – Aran-Fey Sep 13 '17 at 07:56
  • 1
    Decode it and then use some kind of imaging library to load it as an image. If that fails, it's not an image. – Aran-Fey Sep 13 '17 at 07:56
  • Thanks, I used imghdr to check the format of the image if no one format is returned, means that is not a image. – rayitopy Sep 13 '17 at 10:25

1 Answers1

1

Finally i decided to use the library imghdr that comes wiht python. So i saved the base64 image to a file and then I checked the file to know if is a valid image like this:

if imghdr.what(avatar_filename):
    print('is a image')
else:
    print('is not a image')

The imghdr.what() function returns the type of the image, so if no type is returned I'm assuming that is not a image.

rayitopy
  • 111
  • 2
  • 9