将.png图像转换为base64

时间:2017-04-17 06:32:08

标签: python tkinter

我正在尝试将 .png 图像编码为base64,这样人们就不需要让我的图片/更改图片来查看它了。

我经常搜索并尝试了很多东西,我的最后一次尝试给了我这个错误:

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>

我查看了0x8d是什么,但发现没有任何效果或我真正理解。

这是我的代码:

#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))

2 个答案:

答案 0 :(得分:3)

无法真正指出你做错了什么,但代码似乎要复杂得多。

base64模块为您处理

,而不是进行读取操作
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)

还注意到您正在尝试对已编码的string进行编码 查看行base64.b64encode(string)

答案 1 :(得分:0)

当您打开一个非类似文本的文件时,使用'rb'将避免该错误。

相关问题