【问题标题】:Encoding Image to Base64 to MongoDB将图像编码为 Base64 到 MongoDB
【发布时间】:2022-11-30 20:02:38
【问题描述】:

下面是用于尝试完成此操作的 Python 代码。

我正在尝试拍摄图像并将其作为 base64 上传到我的 MongoDB。这个问题是每当我尝试将它放入 MongoDB 时,它都会给我一个不同的字符串。

我添加了将 enc_file 输出到文本文档的代码行,这是正确的 Base64,然后可以将其转换回图像。问题是我在我的 MongoDB 数据库中得到下图中的输出。

import os
import base64
import pymongo

def checkImage(file_name):
    if file_name.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif')):
        return True
    return False

def checkFile(file_name):
    if(os.path.exists(file_name)):
        return True
    return False

def convert64(file_name):
    image_file = open(file_name, "rb")
    bs64_str = base64.b64encode(image_file.read())
    return bs64_str

conn_str = "--"

connection = pymongo.MongoClient(conn_str, serverSelectionTimeoutMS=5000)
db = connection.test
file_meta = db.file_meta

def main():
    while(True):
        file_name = input("Enter the image name to upload: ")
        # check if the file exists or not in our folder
        if checkFile(file_name):
            # verify that the file is an image file
            if checkImage(file_name):
                # print(convert64(file_name))
                enc_file = convert64(file_name)
                coll = db.testcollection
                
                with open('base64.txt', 'wb') as f:
                    f.write(enc_file)
                    
                coll.insert_one({"filename": file_name, "file": enc_file, "description": "test"})
                break;
        else:
            print("Please enter a valid image file")

main()

我希望文本文档的输出与插入到我的 Mongo 数据库中的输出相同。

【问题讨论】:

  • 它给了我一个不同的字符串。- 不仅仅是不同,它是已经 Base64 编码字符串的 Base64 编码版本,(双重编码)将 jpg 图片 /9j/4AAQ... 的 Base64 编码字符串再次编码,你会得到:LzlqLzRBQVE...。我不明白为什么或在哪里发生。

标签: python mongodb base64


【解决方案1】:

希望这对我现在也遇到了这个有帮助。

您将图像转换为 base64,似乎 mongodb 也这样做了,这就是为什么您看到不同的字符串并得到 base64 的 base64。

导入 bson 从 bson 导入二进制文件

with open(image_location, "rb") as img_file:
    my_string = Binary(img_file.read())

my_collection.insert_one({"_id": bson_id_image, "Image": my_string })

【讨论】:

    猜你喜欢
    • 2017-01-09
    • 2016-05-22
    • 1970-01-01
    • 2016-04-13
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多