python - 视频转base64,图片转base64

#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()
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值