【发布时间】:2012-04-02 12:56:29
【问题描述】:
对于保存图像,我尝试使用此代码。
MySqlConnection mycon = new MySqlConnection(string.Format("Server=127.0.0.1;Port=3306;Database=test;Uid=root;Pwd=123456;"));
mycon.Open()
FileStream fs = new FileStream("b.jpg", FileMode.Open, FileAccess.Read);
int sizee = (int)fs.Length;
byte[] rawData = new byte[sizee+1];
fs.Read(rawData, 0, sizee);
fs.Close();
new MySqlCommand(string.Format("INSERT INTO image VALUES(NULL,'{0}',{1})", rawData, sizee), mycon).ExecuteNonQuery();
此代码工作正常并成功插入数据。但是当我尝试检索数据时,它抛出异常找不到适合完成此操作的成像组件。
这是用于检索数据的代码。
MySqlConnection mycon = new MySqlConnection(string.Format("Server=127.0.0.1;Port=3306;Database=test;Uid=root;Pwd=123456;"));
mycon.Open();
MySqlCommand mycom = new MySqlCommand("Select * from image", mycon);
MySqlDataReader myData = mycom.ExecuteReader();
myData.Read();
int filesize = myData.GetInt32(myData.GetOrdinal("size"));
byte[] mydatya=new byte[filesize];
myData.GetBytes(myData.GetOrdinal("myImage"), 0, mydatya, 0, filesize);
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = new MemoryStream(mydatya);
bitmapImage.EndInit();
【问题讨论】:
-
检索代码中的对象是否必须是 BitmapImage 而不是 System.Drawing.Image 对象?我对 BitmapImage 对象不是很熟悉,但错误听起来与此有关。我认为 MySQL 在这里并不是一个真正的因素,而是为了验证我是否会测试完整的循环图像流以确保 byte[] 是您所期望的(也许只是暂时将图像构造代码移动到 Save 方法中验证它能够从原始字节创建图像,而不必担心字节与数据库之间的传输)
-
你不能像这样直接在查询字符串中传递图像数据。要进行测试,请将图像数据作为文件保存到磁盘并尝试打开它。您需要参数化查询,而不是复合查询字符串。