首页 > 解决方案 > HTML中的Python base64 - 损坏的图像

问题描述

我尝试这样做:

HTML 结果:

get_base64_screenshot.py

import mss, cv2, base64
import numpy as np

MSS = mss.mss()

# screenshot
frame_bytes = MSS.grab(MSS.monitors[2])

# BGRA -> RGB
frame_array = np.array(frame_bytes)
frame_array = np.flip(frame_array[:, :, :3], 2)

# resize
frame_resized = cv2.resize(frame_array, (640, 360), interpolation = cv2.INTER_CUBIC)

# base64
frame_base64 = base64.b64encode(frame_resized)

我究竟做错了什么?我认为这是错误的解码。

标签: pythonhtmlimagebase64

解决方案


您将原始 cv2 图像数据编码为 base64,您的 Web 浏览器无法理解。您需要将原始图像数据编码为 jpg,然后对其进行编码。

# resize
frame_resized = cv2.resize(frame_array, (640, 360), interpolation = cv2.INTER_CUBIC)

encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]
result, frame_encoded = cv2.imencode('.jpg', frame_resized, encode_param)

# base64
frame_base64 = base64.b64encode(frame_encoded)

这里获取的代码片段


推荐阅读