我知道我可以使用
将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以外的其他格式,则会获得奖励。
答案 0 :(得分:1)
显然imsave支持“类文件对象”,其中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
答案 1 :(得分:0)
如果你想进行文件上传(任何类型的图片) 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)
代码未经过测试!!!!!!!