zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python 读取图片文件base64编码的两种方式

Python文件编码 方式 图片 读取 两种 base64
2023-09-27 14:29:08 时间
import io
import base64
from PIL import Image


def get_picture_base64_data(image_path):
    with open(image_path, 'rb') as img_obj:
        base64_data = base64.b64encode(img_obj.read())
    # try:
    #
    # except Exception as e:
    #     base64_data = ''

    return base64_data


def decode_base64_str(img_base64_str):
    try:
        decode_str = base64.b64decode(img_base64_str)
    except:
        decode_str = ''

    return decode_str


def get_picture_base64_data_02(image_path):
    img = Image.open(image_path).convert('RGB')
    output = io.BytesIO()
    img.save(output, format='PNG')
    base64_data = output.getvalue()

    return base64_data


if __name__ == "__main__":
    img_path = "./demo.jpg"
    # img_path = "./502_01.jpg"
    print(decode_base64_str(get_picture_base64_data(img_path))[:100])
    print(get_picture_base64_data_02(img_path)[:100])