[Python] Encoding an image file with base64

Discussão em 'Python' iniciado por Stack, Julho 24, 2025.

  1. Stack

    Stack Membro Participativo

    I want to encode an image into a string using the base64 module. I've ran into a problem though. How do I specify the image I want to be encoded? I tried using the directory to the image, but that simply leads to the directory being encoded. I want the actual image file to be encoded.

    EDIT

    I tried this snippet:

    with open("C:\Python26\seriph1.BMP", "rb") as f:
    data12 = f.read()
    UU = data12.encode("base64")
    UUU = base64.b64decode(UU)

    print UUU

    self.image = ImageTk.PhotoImage(Image.open(UUU))


    but I get the following error:

    Traceback (most recent call last):
    File "<string>", line 245, in run_nodebug
    File "C:\Python26\GUI1.2.9.py", line 473, in <module>
    app = simpleapp_tk(None)
    File "C:\Python26\GUI1.2.9.py", line 14, in __init__
    self.initialize()
    File "C:\Python26\GUI1.2.9.py", line 431, in initialize
    self.image = ImageTk.PhotoImage(Image.open(UUU))
    File "C:\Python26\lib\site-packages\PIL\Image.py", line 1952, in open
    fp = __builtin__.open(fp, "rb")
    TypeError: file() argument 1 must be encoded string without NULL bytes, not str


    What am I doing wrong?

    Continue reading...

Compartilhe esta Página