【问题标题】:Cant display images from GridFS, PyMongo无法显示来自 GridFS、PyMongo 的图像
【发布时间】:2018-05-25 14:45:28
【问题描述】:

大家好,我是 Python 新手。 所以我有一个困惑的问题。我需要将图像存储在数据库中,然后我必须在客户端显示每个图像。我正在使用 Flask 进行休息请求。

所以这里我有提交的简单标记

<form action="/upload" method="post" enctype="multipart/form-data">
    <label for="image">Select image</label>
    <input type="file" name='img' id='image'>
    <input type="submit" id='upload_img'>
</form>

我在这里收到我的请求并将其保存到我的数据库中

@app.route("/upload", methods=["POST"])
def upload_image():
    # get current image file
    img_file = request.files['img']
    # get Content Type and File Name of current image
    content_type = img_file.content_type
    filename = img_file.filename

    # save to GridFS my image
    # fields <-- recive the id of just saved image
    fields = db.FS.put(img_file, content_type=content_type, filename=filename)
    # store the filename and _id to another database
    # so here we can much morea easaly get image from our GridFS
    db.Mongo['images'].insert({"filename": filename, "fields": fields})

    return index(images=[])

我的简单数据库模型

class db(object):
   URI = "mongodb://localhost:27017"
   Mongo = None
   FS = None

   @staticmethod
   def initialize():
       client = pymongo.MongoClient(db.URI)
       db.Mongo= client['gallery']
       db.FS = GridFS(Database.DATABASE)

并且所有的保存都成功了。

从数据库中检索我的图像并尝试将其发送到客户端

@app.route('/get_all_images')
   def get_image():
   images = db.Mongo['gallery'].find({})
   # try to get just a first image _id and fing it at GridFS files
   image = db.FS.get(images[0]["fields"])
   #send to the client
   return index(images=image.read())

这是响应中显示图像的标记

    <div>
        <img src="data:image/png;base64,{{images}}" alt="">
        <div>{{images}}</div>
    </div>

最后我得到了这样的东西enter image description here

响应如下所示: b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00w\x00\x00\x00\x7f\x08\x06\x00\x00\x00\xd5j] \xe7\x00\x00\x00\x19tEXtSoftware\x00Adobe ImageReadyq\xc9e

问题是我无法弄清楚如何将此字节格式转换为真实图像..并直接从数据库将其显示在网页上。

我尝试制作几种变体来解决这个问题..但在某些方面我的想法是如何爆炸的..我真的不明白如何使用它。

感谢您的宝贵时间 :)

如果有人有任何 idias 或建议我如何将图像从数据库显示到客户端...

【问题讨论】:

  • 我相信这个问题很常见......但我一开始就坚持这个案例

标签: python image gridfs


【解决方案1】:

我做到了! :)

我自己想出了如何解决这个问题。

实际上问题出在我的回复中……在某些情况下也出在客户端。 因为当我从服务器发送请求时,我发送的是 byte 格式的数据,

 print(type(image.read()))
 <class 'bytes'>

在客户端时,我建议使用 二进制字符串

<img src="data:image/png;base64,{{images}}" alt="">

有我的解决方案代码:

import codecs
base64_data = codecs.encode(image.read(), 'base64')
image = base64_data.decode('utf-8')

在客户端我收到字符串,我将其粘贴到 img 标记中......然后 taddaaaa 我从我的数据库中获取了图像。

感谢所有试图帮助我或想办法解决我的问题的人。

我不确定这是最佳做法,但它确实有效。

附:对不起我的英语:P

【讨论】:

    猜你喜欢
    • 2014-04-08
    • 2017-06-23
    • 2016-04-27
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-21
    • 2012-01-30
    相关资源
    最近更新 更多