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)