#coding: utf-8
#python3
import cv2
import base64
from PIL import Image
from io import BytesIO
# 将np图片(imread后的图片)转码为base64格式
def image_to_base64(image_np,image_type):
image = cv2.imencode(image_type,image_np)[1]
image_code = str(base64.b64encode(image))[2:-1]
return image_code
def frame2base64(frame):
img = Image.fromarray(frame) #将每一帧转为Image
output_buffer = BytesIO() #创建一个BytesIO
img.save(output_buffer, format='JPEG') #写入output_buffer
byte_data = output_buffer.getvalue() #在内存中读取
base64_data = base64.b64encode(byte_data) #转为BASE64
return base64_data #转码成功 返回base64编码
def generate():
camera = cv2.VideoCapture(0)
try:
while True:
ret, frame = camera.read()
base64_data = frame2base64(frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
except Exception as e:
print(e)
finally:
# 释放资源
camera.release()
# cv2.destroyAllWindows()
if __name__ == '__main__':
# 图片转base64
path = '5.jpg'
if os.path.isfile(path):
img = cv2.imread(path)
suffix = path.split(".")[-1]
image_base64 = image_to_base64(img,'.' + suffix)
# 视频转base64
generate()
python - 视频转base64,图片转base64
最新推荐文章于 2024-06-13 02:18:18 发布