如何将C#镜像对象插入MongoDB
本文关键字:对象 插入 MongoDB 镜像 | 更新日期: 2023-09-27 18:00:09
我是mongoDB的新手,我想将一个C#/SQL Server Windows应用程序转换为使用mongoDB作为其DB,我的程序正在从控制台捕获屏幕截图,并将其转换为C#Image对象,然后将其插入SQL Image类型,我的问题是如何在MongoDB中做到这一点,因为我的图像很小,我编写了一个小程序,从sql中读取并将其存储在MongoDB中(在MongoDB中将sql Image类型变为字符串),然后我从MongoDB中读取并尝试将其显示在图片框中,我在内存流中得到了一个错误,这就是错误:后面是我的程序代码。"参数无效。"
public partial class Form1 : Form
{
VideoEntities vid = new VideoEntities();
public Form1()
{
InitializeComponent();
connectToMongo();
}
public void connectToMongo()
{
Utilitys util = new Utilitys();
var con = "mongodb://127.0.0.1";
MongoClient client = new MongoClient(con);
var db = client.GetDatabase("Video");
ObjectResult<getFrame_Result> frame;
List<getFrame_Result> frameList;
frame = vid.getFrame(50604803);
frameList = frame.ToList();
string jsonStr = jsonStr = util.deserialze(frameList[0]);
// jsonStr = "{Frame:" + jsonStr + "}";
jsonStr = jsonStr.Replace("[", "{");
jsonStr = jsonStr.Replace("]", "}");
var frameCollection = db.GetCollection<BsonDocument>("Frame");
var oneFrame = BsonDocument.Parse(jsonStr);
frameCollection.InsertOne(oneFrame);
Byte[] data = new Byte[0];
var collection = db.GetCollection<BsonDocument>("Frame");
var filter = Builders<BsonDocument>.Filter.Eq("id", 50604803);
var result = collection.Find(filter).ToList();
string img = (string)result[0]["Frame"];
data = Encoding.ASCII.GetBytes(img);
MemoryStream mem = new MemoryStream(data);
pictureBox.Image = Image.FromStream(mem);
}
}
有人能帮忙吗?关于如何以正确的方式插入图像数据,使其成为二进制数据?
我终于让它工作了,这是代码:
public partial class Form1 : Form
{
VideoEntities vid = new VideoEntities();
public Form1()
{
InitializeComponent();
connectToMongo();
}
public void connectToMongo()
{
Utilitys util = new Utilitys();
var con = "mongodb://127.0.0.1";
MongoClient client = new MongoClient(con);
var db = client.GetDatabase("Video");
ObjectResult<getFrame_Result> frame;
List<getFrame_Result> frameList;
frame = vid.getFrame(50604803);
frameList = frame.ToList();
**var frameCollection = db.GetCollection<getFrame_Result>("Frame");**
frameCollection.InsertOne(frameList[0]);
Byte[] data = new Byte[0];
var collection = db.GetCollection<BsonDocument>("Frame");
var filter = Builders<BsonDocument>.Filter.Eq("_id", 50604803);
var result = collection.Find(filter).ToList();
data = (Byte[]) result[0]["Frame"];
MemoryStream mem = new MemoryStream(data);
pictureBox.Image = Image.FromStream(mem);
}
}
更改介于***刚刚将get集合中的类型更改为我需要插入MongoDb的类,现在它正在插入我可以获得并显示为图像的二进制数据