python - HTML中的Python base64 - 损坏的图像
问题描述
我尝试这样做:
- 使用 python-mss 截图
- 调整大小然后转换为base64
- 使用 python-flask 请求处理程序通过 ajax 加载 JS 并将结果粘贴到 img 标记中的 src 属性,例如
data:image/png;base64,{{base64}}
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)
我究竟做错了什么?我认为这是错误的解码。
解决方案
您将原始 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)
推荐阅读
- mysql - 如何将表格行值作为列
- javascript - 在 Github API 中按星数对用户存储库进行排序
- xml - How to use Sed/xmlparser to update multi line with many uniode characters
- javascript - Determine if two coordinates are within desired radius
- javascript - 可以在将元素返回到新数组之前过滤操作元素吗?
- mysql - Convert SQL Query to ORM Query
- android - 有什么办法可以避免在 Android(Kotlin) 中连续输入相同的代码
- ios - 如果我使用 unwindSegue 从屏幕 A 转到 B 再到 C 又回到 B,如何返回主显示器 (A)
- gradle - 如何在 Gradle 中创建可传递的分层多项目?
- python-3.x - 如何为python中的每个值分配数字