Search code examples
pythonimageimage-processingpython-imaging-libraryreportlab

base64 URI to PNG-Python


I am trying to generate a PDF via Python using "ReportLab" and I would like to add an image to it. The image that I have to use is a PNG but it has this format:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA+gAAAH0CAYAAACuKActAAAgAEf (and it continues)

I don't know very well what to do, first I think that I need to transform that URI to an image but i don't know how to do it and then, use something like:

import Image
im = Image.open("infile.png")
im.save("outfile.jpg")

In order to convert the .PNG to .JPG. Can someone help me?


Solution

  • Try this (edit: Thanks to njzk2 for pointing out to cut the header):

    import Image, io, base64
    
    data = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
    
    im = Image.open(io.BytesIO(base64.b64decode(data.split(',')[1])))
    im.save("image.jpg")
    

    Added a real base64 string for testing from here, this should result in an image of a little red dot: red dot