4

I am trying to encode .png images to base64 so people don't need to have my pictures/change pictures to view it.

I have searched a lot and tried many things, my last attempt got me this error:

Traceback (most recent call last):
  File "random.py", line 100, in <module>
    convert(r"C:\Users\simon\Desktop\pictures\pizza_pics\meat_lovers.png")
  File "random.py", line 91, in convert
    data = f.read()
  File "C:\Users\simon\AppData\Local\Programs\Python\Python36-32\lib\encodings\c  p1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 30: chara  cter maps to <undefined>

I looked into what 0x8d is but found nothing that worked or that I really understood.

This is my code:

#encodes the images from .jpg or .png files to base64 string(lets others view the image)
def convert(image):
    img = open(image)
    data = img.read()

    string = base64.b64encode(data)
    convert = base64.b64encode(string)

    img = Image.open(r"C:\Users\simon\Desktop\pictures\pizza_pics\meat_lovers.png", "UTF-8")
    img.write(convert)

if __name__ == "__main__":
    convert(r"C:\Users\simon\Desktop\pictures\pizza_pics\meat_lovers.png")

#shows the image
img.thumbnail((350, 200), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(image = img)
label_image = tk.Label(image = photo)
label_image.grid(column=0, row=2, padx=(5, 95))
Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
simmo
  • 123
  • 1
  • 2
  • 11

2 Answers2

6

Cant really put my finger on what you are doing wrong, but the code seems to be more complex then it has to be.

Instead of doing the read operations, let base64 module handle it for you

import base64
with open('noaa19-161015.png', 'rb') as fp, open('test.b64', 'w') as fp2:
    base64.encode(fp, fp2)

with open('test.b64', 'rb') as fp, open('test.png', 'wb') as fp2:
    base64.decode(fp, fp2)

Also noticed that you are trying to encode a already encoded string look at the row base64.b64encode(string)

David Bern
  • 778
  • 6
  • 16
0

while you're opening a not txt-like file, using 'rb' will avoid that error.

Noodle
  • 27
  • 1
  • 9
  • oh so "rb" is for images without text? interesting, thank you! – simmo Apr 17 '17 at 08:05
  • 1
    for an explanation for the use of 'rb' have look at this link http://stackoverflow.com/questions/9644110/difference-between-parsing-a-text-file-in-r-and-rb-mode/9644141#9644141 Im running Linux, so there might be a difference there – David Bern Apr 17 '17 at 08:07
  • ah i'm on windows using that too i think, not sure to be honest but i'll take a look thank you! – simmo Apr 17 '17 at 09:31