base64编码图像; binascii.Error:无效的base64编码

时间:2020-03-20 19:49:43

标签: python python-3.x anaconda

作为一个课程的项目,我正在使用python开发图像编码器/解码器,但是似乎有点卡住了,我真的很想得到一些帮助

我得到的错误是:

runfile('D:/Documentos/Python/Proyecto_Final/Main.py', wdir='D:/Documentos/Python/Proyecto_Final')
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\...\anaconda3\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "D:\Documentos\Python\Proyecto_Final\Main.py", line 32, in decode64
    imagen.write(base64.decodebytes(baset.encode()))
  File "C:\...\anaconda3\lib\base64.py", line 546, in decodebytes
    return binascii.a2b_base64(s)
binascii.Error: Invalid base64-encoded string: number of data characters (1) cannot be 1 more than a multiple of 4

我的代码是:

from tkinter import *
import os
import base64

def browseBtn():
    filename = filedialog.askopenfilename()
    texto.insert(0, filename)

def convbase64():
    path = str(texto.get())
    imagen = open(path, 'rb')
    leeimg = imagen.read()
    codigo64 = base64.encodebytes(leeimg)
    texto2.insert("1.0", codigo64)

def decode64():
    myFormats = [('JPEG / JFIF','*.jpg'),\
                     ('Portable Network Graphics','*.png'),\
                     ('Windows Bitmap','*.bmp'),('CompuServer GIF','*.gif'),]
    baset = texto2.get(1.0)
    filepath = filedialog.asksaveasfilename(filetypes=myFormats)
    imagen = open(filepath, 'wb')
    imagen.write(base64.decodebytes(baset.encode()))
    imagen.close()

ventana = Tk()
ventana.title("Convertidor imagen a Base64")
ventana.geometry("800x480")
letrero = Label(ventana, text = "Imagen:")
texto = Entry(ventana, width = 100)
buscarImg = Button(ventana, text = "Elegir", command=browseBtn)
letrero2 = Label(ventana, text = "codigo base64:")
texto2 = Text(width = 75, height = 1)
btnconvertir = Button(ventana, text = "Codificar", command=convbase64)
btndecodificar = Button(ventana, text = "decodificar", command=decode64)
letrero.place(x = 32, y = 32)
letrero2.place(x = 16, y = 64)
texto.place(x = 114, y = 35)
texto2.place(x = 114, y = 69)
buscarImg.place(x = 724, y = 32)
btnconvertir.place(x = 724, y = 64)
btndecodificar.place (x = 724, y = 96)

ventana.mainloop()

我正在使用水蟒的Spyder 3.7

1 个答案:

答案 0 :(得分:1)

使用Text.get获得多个字符时,需要给它一个结束位置。您可以为此使用特殊字符串"end",但忽略tkinter用"end-1c"添加的最后一个换行符:

baset = texto2.get("1.0", "end-1c")

有关更多信息,请参见this answer