Display image of a binary PNG file 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 binary format and I would like to display it. How can i do this in python?

I established a database connection with pymongo, but I have no idea how I can decode a byte stream. Keep in mind that I did not create this database, I only have access to it.

+4
source share
2 answers

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

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()
-1

, , Pillow

import sys
from cStringIO import StringIO

from bson.binary import Binary
from pymongo import MongoClient
from PIL import Image

data = open(sys.argv[1], 'rb').read()

client = MongoClient()
db = client.so
db['images'].remove()
db['images'].insert({'id': 1, 'img': Binary(data)})

for rec in db['images'].find():
    im = Image.open(StringIO(rec['img']))
    im.show()

script PNG , Mongo, , ,

+2

Source: https://habr.com/ru/post/1670876/


All Articles