图片base64与PIL互转python代码

正常来说我们无法用json格式来传输图片的,我们需要将图片文件转换为base64格式,从而可以用json格式来传输,下面介绍两种格式互转的python代码

1、PIL转base64

import base64
from io import BytesIO
from PIL import Image


def PIL_to_base64(image):
    output = BytesIO()
    image.save(output,format='png')
    contents = output.getvalue()
    output.close()
    string = base64.b64encode(contents)
    return string

2、base64转PIL

import base64
import six
from PIL import Image

def base64_to_PIL(string):
    """
    base64 string to PIL
    """
    try:    
            base64_data = base64.b64decode(string)
            buf = six.BytesIO()
            buf.write(base64_data)
            buf.seek(0)
            img = Image.open(buf).convert('RGB')
            return img
    except:
        return None
0

Leave a Reply

Your email address will not be published.