Python / PIL: Create and save image from data uri

后端 未结 3 1958
温柔的废话
温柔的废话 2020-12-15 06:14

I have a url like so

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxITEhUUEhQUFRUXGBcVFxgXFxUXGBQYGBYXGBQWFRUYHCggGB0lHBQXITIhJSkrLi4uFyAzODMsN         


        
3条回答
  •  遥遥无期
    2020-12-15 06:50

    There's nothing in the stdlib to parse data: URIs beyond pulling out the path. But it's not hard to parse the rest yourself. For example:

    import urllib.parse
    
    up = urllib.parse.urlparse(url)
    head, data = up.path.split(',', 1)
    bits = head.split(';')
    mime_type = bits[0] if bits[0] else 'text/plain'
    charset, b64 = 'ASCII', False
    for bit in bits:
        if bit.startswith('charset='):
            charset = bit[8:]
        elif bit == 'base64':
            b64 = True
    
    # Do something smart with charset and b64 instead of assuming
    plaindata = data.decode("base64")
    
    # Do something smart with mime_type
    with open('spam.jpg', 'wb') as f:
        f.write(plaindata)
    

    (For Python 2.x, just change urllib.parse to urlparse.)

    Notice that I didn't use PIL at all. You don't need PIL to save raw image data to a file. If you want to make an Image object out of it first, e.g., to do some post-processing, of course you can, but it's not relevant to your question.

提交回复
热议问题