簡體   English   中英

在pymongo API中使用圖像

[英]working with images in pymongo API

我正在做一個pymongo連接程序,該程序使用python在mongodb上創建gridfs數據庫並將圖像添加到數據庫中。我已經使用命令行解析器調用了這些方法。我已經成功將圖像添加到了db中,並且它還反映了mongodb db,但是當我調用show函數時,它說找不到圖像。 這是代碼:

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

以下是操作:

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

在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"
    }

我不知道問題是什么我在fedora中完成了相同的程序。但是在Windows im中,這個問題是與操作系統或python版本有關的

您可能需要使用BytesIO類將im_stream轉換為字節以進行讀取。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM