Search code examples
pythonpython-3.xtkinterhttplib2

How can I use httplib2 to upload an image, but not save it to my computer?


How can I use httplib2 to receiving images from the site, but not save it to my computer, but at the same time so that I can use it. My code is:

h = httplib2.Http('.cache')
response, content = h.request(self.url + 'v1588505946/images/mc-donalds_vexbhd.png')
out = open('images2/' + self.names[1], 'wb')
out.write(content) # How to avoid this line
out.close()
self.img1 = Image.open('images2/' + self.names[1]) # Here I want to open the image directly from the server
self.img1 = ImageTk.PhotoImage(self.img1)

Solution

  • Use BytesIO to convert it directly,then you could use Image.open to open it directly. example:

    from io import BytesIO
    
    ...
    
    response, content = h.request(self.url + 'v1588505946/images/mc-donalds_vexbhd.png')
    self.img1 = Image.open(BytesIO(content))