0

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.

Mutant Bob
  • 3,121
  • 2
  • 27
  • 52

2 Answers2

1

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
Mutant Bob
  • 3,121
  • 2
  • 27
  • 52
0

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!!!!!!!

Community
  • 1
  • 1
user2740652
  • 361
  • 3
  • 12
  • Actually, I'm transmitting the PNG as an HTTP server not client. And I absolutely do not want there to be a temporary file. – Mutant Bob Apr 28 '16 at 14:30
  • what do you use for server? --- I think what you can do is, set server header to tell the client it's a picture and then you print/echo the image. – user2740652 Apr 29 '16 at 07:14
  • server.HTTPServer with a custom class derived from BaseHTTPRequestHandler – Mutant Bob Apr 29 '16 at 18:28