日日行,不怕千万里;常常做,不怕千万事|

__username

园龄:2年4个月粉丝:12关注:2

📂python
🔖Python
2023-08-22 16:13阅读: 415评论: 0推荐: 0

图片转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 @   __username  阅读(415)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!

本文作者:DIVMonster

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

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

点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起