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) |
| |
| |
| |
| 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" |
| 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') |
| binary_content = img_byte.getvalue() |
| |
| 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.save('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") |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!