Python / PIL: Create and save image from data uri

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

I have a url like so

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


        
相关标签:
3条回答
  • 2020-12-15 06:41

    I will assume you have just the base64 part saved in a variable called data. You want to use Python's binascii module.

    from binascii import a2b_base64
    
    data = 'MY BASE64-ENCODED STRING'
    binary_data = a2b_base64(data)
    
    fd = open('image.png', 'wb')
    fd.write(binary_data)
    fd.close()
    

    No PIL needed! (thank goodness! :)

    0 讨论(0)
  • 2020-12-15 06:44

    To expand on the comment from Stephen Emslie, in Python 3 this works and is less code:

    data = 'data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUAAAhwAAAFoCAYAAAA.......'
    response = urllib.request.urlopen(data)
    with open('image.jpg', 'wb') as f:
        f.write(response.file.read())
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题