2016-10-15 7 views
0

pythonを使用してmongodb上にgridfsデータベースを作成し、データベースに画像を追加するpymongo接続プログラムを実行しています。コマンドラインパーサーを使用してメソッドを呼び出しました。 db内のイメージとmongodb dbにも反映されますが、show関数を呼び出すとイメージが見つかりません。ここ はコードです:後pymongo APIで画像を操作する

import argparse 
from PIL import Image 
from pymongo import Connection 
import gridfs 
from bson.binary import Binary 
# setup mongo 
MONGODB_HOST = 'localhost' 
MONGODB_PORT = 27017 
# connect to the database & get a gridfs handle 
mongo_con = Connection(MONGODB_HOST, MONGODB_PORT) 
fs = gridfs.GridFS(mongo_con.ank1) 

def add_image(): 
    """add an image to mongo's gridfs""" 
    gridfs_filename = 'ofc2.jpg' 
    fileID = fs.put(open('C:\Python27\ofc2.jpg','r'),filename='ofc2.jpg') 
    print "created new gridfs file {0} with id {1}".format(gridfs_filename, fileID) 

def show(): 
    """start the flask service""" 
    filename='ofc2.jpg' 
    if not fs.exists(filename="ofc2.jpg"): 
     raise Exception("mongo file does not exist! {0}".format(filename)) 
    im_stream = fs.get_last_version(filename) 
    im = Image.open(im_stream) 
    im.show() 

def main(): 
    # CLI 
    parser = argparse.ArgumentParser() 
    parser.add_argument('--show', action='store_true', help='start the service') 
    parser.add_argument('--add', action='store_true', help='add an image via URL') 
    args = parser.parse_args() 
    if args.show: 
     show() 
    elif args.add: 
     add_image() 

main() 

はOPです:MongoDBの

MongoDBの出力

MongoDB Enterprise > show dbs; 
ank    0.000GB 
ank1   0.000GB 
ankit   0.000GB 
gridfs_example 0.000GB 
local   0.000GB 
MongoDB Enterprise > use ank1 
switched to db ank1 
MongoDB Enterprise > show collections 
fs.chunks 
fs.files 
MongoDB Enterprise > db.fs.files.find().pretty() 
    { 
    "_id" : ObjectId("5802397f0f84ea122c6176a6"), 
    "chunkSize" : 261120, 
    "filename" : "ofc2.jpg", 
    "length" : 335, 
    "uploadDate" : ISODate("2016-10-15T14:13:19.882Z"), 
    "md5" : "ef937ff6e6a00e64a2dda34251ca03b5" 
    } 

上の `

D:\>python img.py 

D:\>python img.py 

D:\>python img.py --add 
created new gridfs file ofc2.jpg with id 580237fb0f84ea10789b20e6 

D:\>python img.py --show 
Traceback (most recent call last): 
    File "img.py", line 62, in <module> 
    main() 
    File "img.py", line 57, in main 
    show() 
    File "img.py", line 47, in show 
    im = Image.open(im_stream) 
    File "C:\Python27\lib\site-packages\PIL\Image.py", line 1980, in open 
    raise IOError("cannot identify image file") 
    IOError: cannot identify image file 

私は問題が何であるかを知りませんそれは同じ問題を抱えていますが、OSに関連する問題ですe Pythonのバージョン

+0

こんにちはは、代わりに出力して画像を投稿し、あなたがそれをコピーして貼り付けてください可能性があり、それは--showで、同じ出力を助けなかった – lrnzcig

答えて

0

im_streamを、BytesIOクラスを使用して読み込むためにバイトに変換する必要がある場合があります。

im = Image.open(io.BytesIO(im_stream.read()), 'r') 
+0

を読みやすくなります。 – Ankit

+0

あなたが使用しているPython/PIL/pymongo/mongodbのバージョンを確認できますか? –

+0

python 2.7.9pymongo – Ankit