Reputation: 3549
I know I can save an RGB array to a file using
from matplotlib.pyplot import imsave
rgb = numpy.zeros([height,width,3], dtype=numpy.uint8)
paint_picture(rgb)
imsave("/tmp/whatever.png", rgb)
but now I want to write the PNG to a byte buffer instead of a file so I can later transmit those PNG bytes via HTTP. There must be no temporary files involved.
Bonus points if the answer has variations that support formats other than PNG.
Upvotes: 0
Views: 1285
Reputation: 3549
Evidently imsave supports "file-like objects" of which io.BytesIO is the one I need:
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
Upvotes: 1
Reputation: 361
If you want to do a file upload (any type of picture) Send file using POST from a Python script
But if you want to send raw png data you can reread the file and encode it in base64. Your server just have to decode base64 and write the file.
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)
Code not tested!!!!!!!
Upvotes: 0