图片转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")
本文来自博客园,作者:__username,转载请注明原文链接:https://www.cnblogs.com/code3/p/17648838.html