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

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)


# or ==============
import json
import cv2
import base64
def cv2_to_base64(image):
    data = cv2.imencode('.jpg', image)[1]
    return base64.b64encode(data.tostring()).decode('utf8')
cv2_to_base64(cv2.imread(r"E:\Code\Python\haddle_ocr\2.png"))  # 图片路径

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")
posted @ 2023-08-22 16:13  __username  阅读(333)  评论(0编辑  收藏  举报

本文作者:DIVMonster

本文链接:https://www.cnblogs.com/guangzan/p/12886111.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。