4

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.

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

for python3 we have to from io import BytesIO and im = Image.open(BytesIO(rec['img']))
@thanasisp indeed, good point, from the OP's question, I assumed that he/she is using Python 2.X (judging by the output sample)
0

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

2 Comments

To the people downvoting, please expain what's wrong with this solution and why the other one is better.
f.write(item[u'files'][u'screenshot']) is showing following error TypeError: argument 1 must be convertible to a buffer, not GridOut

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.