简体   繁体   English

编码Image到Base64到MongoDB

[英]Encoding Image to Base64 to MongoDB

Below is the Python code that am using to try to get this done.下面是用于尝试完成此操作的 Python 代码。

I am trying to take an image and upload that to my MongoDB as base64. This issue is that whenever I try to put it into MongoDB it is giving me a different string.我正在尝试拍摄图像并将其作为 base64 上传到我的 MongoDB。这个问题是每当我尝试将它放入 MongoDB 时,它都会给我一个不同的字符串。

I added the line of code to output enc_file to a text document, and that is the correct Base64 which can then be converted back to an image.我将代码行添加到 output enc_file 到文本文档,这是正确的 Base64,然后可以将其转换回图像。 The issue is that I am getting the output in the image below in my MongoDB Database.问题是我在我的 MongoDB 数据库中得到下图中的 output。

在此处输入图像描述

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

I am expecting the output from the text document to be the same output that is inserted into my Mongo Database.我希望文本文档中的 output 与插入到我的 Mongo 数据库中的 output 相同。

I just ran into this now as well.我现在也遇到了这个。

You are turning the image into base64 and it seems mongodb does it as well, that is why you are seeing a different string -- you are getting a base64 of a base64.您正在将图像转换为 base64 并且 mongodb 似乎也这样做,这就是您看到不同字符串的原因——您得到的是 base64 的 base64。

import bson
from bson import Binary

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM