使用 python 如何将 RGB 数组转换为适合通过 HTTP 传输的编码图像?

Using python how do I convert an RGB array to an encoded image suitable for transmission via HTTP?

我知道我可以使用

将 RGB 数组保存到文件中
from matplotlib.pyplot import imsave
rgb = numpy.zeros([height,width,3], dtype=numpy.uint8)
paint_picture(rgb)
imsave("/tmp/whatever.png", rgb)

但现在我想将 PNG 写入字节缓冲区而不是文件,以便稍后可以通过 HTTP 传输这些 PNG 字节。必须没有涉及临时文件。

如果答案有支持 PNG 以外格式的变体,则加分。

如果要上传文件(任何类型的图片) Send file using POST from a Python script

但是,如果您想发送原始 png 数据,您可以重新读取文件并将其编码为 base64。您的服务器只需解码 base64 并写入文件。

import base64
from urllib.parse import urlencode
from urllib.request import Request, urlopen

array_encoded = ""

with open("/tmp/whatever.png") as f:
    array_encoded = base64.encode(f)

    url = 'https://URL.COM' # Set destination URL here
    post_fields = {'image': array_encoded}     # Set POST fields here

    request = Request(url, urlencode(post_fields).encode())
    responce = urlopen(request).read()
    print(responce)

代码未经测试!!!!!!!

显然 imsave 支持 "file-like objects" 其中 io.BytesIO 是我需要的:

buffer = BytesIO()
imsave(buffer, rgb)
encoded_png = buffer.getbuffer()

#and then my class derived from BaseHTTPRequestHandler can transmit it as the response to a GET
self.send_response(200)
self.send_header("Content-Type", "image/png")
self.end_headers()

self.wfile.write(encoded_png)
return