Search code examples
pythonmongodbpymongobytestream

Display image of PNG binary that is stored in MongoDB


I have a mongodb collection that looks something like this:

{
 u'_id': u'someid',
 u'files': {u'screenshot': Binary('\x89PNG\r\n\x1a\n\...', 0)}
}

The screenshot is in a binary format and I would like to display it. How would I do this in python?

I've setup a connection to the database with pymongo but I have no idea how I can decode the bytestream. Bear in mind that I did not create this database, I only have access to it.


Solution

  • Someone answered to the question and then deleted his answer, I don't know why he deleted it because it helped me. The following two lines were his contribution:

    with open('output.png', 'wb') as f:
        f.write(item[u'files'][u'screenshot'])
    

    Then I used Tkinter to display the image:

    from Tkinter import *
    root = Tk()
    
    topFrame = Frame(root)
    topFrame.pack()
    
    screenshot = PhotoImage(file="output.png")
    label_screenshot = Label(topFrame, image=screenshot)
    label_screenshot.pack()
    
    root.mainloop()