[Solved]-Save Base64 String into Django ImageField

4πŸ‘

βœ…

I found the solution.

I need to use only the parte without data:image/jpeg;base64,

In Python, we can do it with something like this:

image_base64 = image_base64.split('base64,', 1 )

6πŸ‘

I think this will be a best approach tried it and tested in django 1.10. based on this SO answer: https://stackoverflow.com/a/28036805/6143656

I made a function for decoded base64 file.

def decode_base64_file(data):

    def get_file_extension(file_name, decoded_file):
        import imghdr

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

        return extension

    from django.core.files.base import ContentFile
    import base64
    import six
    import uuid

    # Check if this is a base64 string
    if isinstance(data, six.string_types):
        # Check if the base64 string is in the "data:" format
        if 'data:' in data and ';base64,' in data:
            # Break out the header from the base64 content
            header, data = data.split(';base64,')

        # Try to decode the file. Return validation error if it fails.
        try:
            decoded_file = base64.b64decode(data)
        except TypeError:
            TypeError('invalid_image')

        # Generate file name:
        file_name = str(uuid.uuid4())[:12] # 12 characters are more than enough.
        # Get the file name extension:
        file_extension = get_file_extension(file_name, decoded_file)

        complete_file_name = "%s.%s" % (file_name, file_extension, )

        return ContentFile(decoded_file, name=complete_file_name)

Then you can call the function

import decode_base64_file

p = Post(content='My Picture', image=decode_based64_file(your_base64_file))
p.save()
πŸ‘€Shift 'n Tab

-1πŸ‘

fh = open("imageToSave.png", "wb")
fh.write(imgData.decode('base64'))
fh.close()

Edit (klaus-d): The code above gives an example, how to store an image file from BASE64 encoded data. It opens a file imageToSave.png in binary mode for writing, then decodes the base64 image data and write the result to the file. At the end it closes the file descriptor.

πŸ‘€onkar

Leave a comment