图片转base64,base64转图片,图片对象转图片字节,图片字节转图片对象

发布时间 2023-08-22 16:21:19作者: __username

demo

图片转base64

def image_to_base64(image_path):
    import base64
    with open(image_path, "rb") as image_file:
        image_data = image_file.read()
        base64_encoded = base64.b64encode(image_data).decode("utf-8")
        return base64_encoded

image_path = r"E:\Code\Python\yolov5py38\dataset\dog_and_cat\images\val\119.jpg"  # 替换为你的图片路径
base64_image = image_to_base64(image_path)
print(base64_image)

base64转图片

def base64_to_image(base64_data, output_path):
    image_data = base64.b64decode(base64_data)
    with open(output_path, "wb") as image_file:
        image_file.write(image_data)

base64_encoded_image = "base64_encoded_data_here"  # 替换为实际的Base64编码
output_path = "output_image.jpg"  # 替换为输出图片的路径和文件名

base64_to_image(base64_encoded_image, output_path)
print("Image saved:", output_path)

图片转换成图片字节

def image_to_bytes():
    from PIL import Image
    from io import BytesIO
    im = Image.open("img.png")
    new_img = im.convert("RGB")
    img_byte = BytesIO()
    new_img.save(img_byte, format='PNG') # format: PNG or JPEG
    binary_content = img_byte.getvalue()  # im对象转为二进制流

    print(binary_content)

image_to_bytes()

图片字节转换成image对象

"""

from io import BytesIO
from PIL import Image


def bytes_to_image(img_byte):
    bytes_stream = BytesIO(img_byte)
    image = Image.open(bytes_stream)   # image对象
    image.save('output_image.jpg')  # 将图片保存到当前目录下的 output_image.jpg 文件中

with open('img.png', 'rb') as f:
    img_byte = f.read()   # 图片字节
    print(img_byte)

bytes_to_image(img_byte)
print("Image saved: output_image.jpg")