0

I'm trying to encode an image using base64 and add it to a MySQL database. I am then trying to pull that code and decode it back to write it to an image locally. Currently I am storing the encoded base64 in a LONGTEXT field that has a Character Set of 'utf8mb4'.

When I try pulling the code down from the database and load it into an image, the image I get cannot be opened. What am I doing wrong?

Here is the code I am using to encode the image file.

def convertImageToJSON():

# pick an image file you have in the working directory
# or give full path
    image = open('/Users/************/Desktop/dog.jpg', 'rb')
    image_read = image.read()
    image_64_encode = base64.encodestring(image_read)
    return image_64_encode

I am storing what is returned by this function in my LONGTEXT field.

I am then trying to make the image using what is in this field for a specific entry

def makeImageFile(name):
    mycursor = mydb.cursor()

    mycursor.execute("SELECT code FROM images WHERE name=name")

    myresult = mycursor.fetchone()

    tester = ''.join(myresult)

    real = tester.encode('utf-8')


    test = base64.decodestring(real)
    print(test)
    image_result = open('deer_decode.jpg', 'wb')
    image_result.write(real)

I use ''.join(myresult) to get it out of a tuple then I use tester.encode('utf-8') to bring it back into utf-8 so that I can use base64.decodestring() (without doing this I get a Type Error)

MikeS
  • 11
  • 2
  • "Currently I am storing the encoded base64 in a LONGTEXT field that has a Character Set of 'utf8'. When I try pulling the code down from the database and load it into an image, the image I get cannot be opened." You sure you connected with utf8 charset? ` Check this https://stackoverflow.com/questions/6202726/writing-utf-8-string-to-mysql-with-python – Raymond Nijland Oct 02 '18 at 14:17
  • @RaymondNijland yes – MikeS Oct 02 '18 at 14:56
  • Are you sure the base64 string is valid. As in it's not being truncated somewhere? You can try decoding it in an online tool. http://www.base64-decoder.com/ will let you decode to a file. You can see if it works there. If you get an error then I'd check your encoding again or see if the string isn't getting truncated. – Jonathan S. Oct 06 '18 at 03:29

0 Answers0