[英]Python output numpy array as base64 encoded string instead of jpg
I have a simple Python3 script that is creating an image from a numpy array using the following...我有一个简单的 Python3 脚本,它使用以下命令从 numpy 数组创建图像...
cv2.imwrite("finalImage.jpg", numpyArray)
This is working correctly but now I am looking to output a base64 encoded string instead of the jpg image.这工作正常,但现在我想输出一个 base64 编码的字符串而不是 jpg 图像。
I know I can convert the output jpg image to a base64
string but is there a way to do this directly so I can skip the extra step of outputting the JPG?我知道我可以将输出的 jpg 图像转换为
base64
字符串,但是有没有办法直接做到这一点,这样我就可以跳过输出 JPG 的额外步骤?
import base64
_, imagebytes = cv2.imencode('.jpg', numpyArray)
print(base64.b64encode(imagebytes))
You can make use of imencode(..)
[opencv-doc] to write the image to a memory buffer:您可以使用
imencode(..)
[opencv-doc]将图像写入内存缓冲区:
success, buffer = cv2
.imencode('.jpg', numpyArray
)
You can then for example base64 encode this:然后你可以例如 base64 编码:
from base64 import b64encode
encoded_image =
b64encode(buffer)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.