Reputation: 4475
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.
Upvotes: 4
Views: 2485
Reputation: 4475
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()
Upvotes: 0
Reputation: 13097
one might use for example 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()
this script takes a PNG file as its first argument, inserts its binary representation into a Mongo collection, retrieves this binary representation and finally displays the figure
Upvotes: 3