【问题标题】:converting .png images to base64将 .png 图像转换为 base64
【发布时间】:2017-09-12 18:26:48
【问题描述】:

我正在尝试将 .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))

【问题讨论】:

  • 感谢您为我编辑代码,我现在知道该怎么做了哈哈

标签: python tkinter


【解决方案1】:

我真的不能指出你做错了什么,但代码似乎比它必须复杂得多。

不做读取操作,让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)

【讨论】:

  • 所以第一个用编码它,第二个解码它?我明白了,谢谢!
  • 我必须将两者都放入我的编码中还是只放入其中的编码部分?
  • 视情况而定。如果你想两者都做,那么两者都用。上半部分将二进制图片编码为Base64,另一部分将base64解码为二进制
  • 我用'wb'表示fp2
  • b64 文件只包含字符。功能上可能没有区别。
【解决方案2】:

当您打开一个非 txt 格式的文件时,使用 'rb' 将避免该错误。

【讨论】:

  • 哦,所以“rb”适用于没有文字的图像?有趣,谢谢!
  • 有关“rb”使用的解释,请查看此链接stackoverflow.com/questions/9644110/…我正在运行 Linux,因此可能存在差异
  • 啊,我想我也在 Windows 上使用它,我不确定,但我会看看谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-01-08
  • 2022-12-25
  • 2017-07-02
  • 1970-01-01
  • 2011-10-21
  • 2018-06-26
  • 2021-09-12
  • 2022-10-05
相关资源
最近更新 更多