[Python] Cannot convert base64 string into image

Discussão em 'Python' iniciado por Stack, Janeiro 17, 2025.

  1. Stack

    Stack Membro Participativo

    Can someone help me turn this base64 data into image? I don't know if it's because the data was not decoded properly or anything else. Here is how I decoded the data:

    import base64

    c_data = { the data in the link (string type) }

    c_decoded = base64.b64decode(c_data)


    But it gave the error Incorrect Padding so I followed some tutorials and tried different ways to decode the data.

    c_decoded = base64.b64decode(c_data + '=' * (-len(c_data) % 4))

    c_decoded = base64.b64decode(c_data + '=' * ((4 - len(c_data) % 4) % 4)


    Both ways decoded the data without giving the error Incorrect Padding but now I can't turn the decoded data into image.
    I have tried creating an empty png then write the decoded data into it:

    from PIL import Image

    with open('c.png', 'wb') as f:
    f.write(c_decoded)
    image = Image.open('c.png')
    image.show()


    It didn't work and gave the error: cannot identify image file 'c.png'
    I have tried using BytesIO:

    from PIL import Image
    import io
    from io import BytesIO

    image = Image.open(io.BytesIO(c_decoded))
    image.show()


    Now it gave the error: cannot identify image file <_io.BytesIO object at 0x0000024082B20270>
    Please help me.

    Continue reading...

Compartilhe esta Página