2016-08-03 53 views
1

我是mongoDB的新手,我想将C#/ SQL Server Windows应用程序转换为使用MongoDB作为其数据库,我的程序从控制台捕获屏幕截图并将其转换为C#Image对象并将其插入到Sql Image类型, 我的问题是我如何做到这一点在MongoDB中,我的图片很小, 我wort一个小程序,从sql读取并将其存储在MongoDB中,(在MongoDB中的SQL图像类型成为一个字符串),然后我从MongoDB中读取并尝试在图片框中显示它,并且在内存流中出现错误,这是错误:后面是我的程序代码。 “参数无效”。如何将C#图像对象插入到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); 

    } 
} 

任何一个可以帮助?如何插入图像数据以正确的方式,因此会去作为二进制数据?

回答

1

我终于得到它的工作,这是代码:

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

    } 
} 

变化是间**只是获取集合类中改变的类型,我需要插入到MongoDB的,现在它插入二进制数据,我可以得到并显示为图像

相关问题