【发布时间】:2017-03-24 18:41:58
【问题描述】:
经过一段时间的尝试并在这里寻找一些答案后,我无法从 MySQL 加载图像。
基本上,用户从OpenFileDialog 中选择一张图片,然后将其加载到PictureBox 中(这工作正常)。
然后用户单击一个按钮,该按钮将通过将图片转换为byte[] 将图片保存在数据库中。
最后,当我尝试在另一个PictureBox 中加载图片时,全黑了。
添加图片到db时:
public void PictureToDB(Image img)
{
MemoryStream tmpStream = new MemoryStream();
img.Save(tmpStream, ImageFormat.Png);
tmpStream.Seek(0, SeekOrigin.Begin);
byte[] imgBytes = new byte[5000];
tmpStream.Read(imgBytes, 0, 5000);
string query = "Update TABLE Set IMG = @imgBytes";
MySqlParameter param = new MySqlParameter("@img", imgBytes);
//Skipping connection to db and all... it works
}
从数据库中获取图片:
public void DBToPicture()
{
string query = "Select IMG From TABLE Where ...";
//Skipping Command lines ...
MySqlDataReader reader = command.ExecuteReader();
DataTable myDT.Load(reader);
Byte[] data = new Byte[0];
data = (Byte[])(myDT.Rows[0]["PHOTOLOISANT"]);
MemoryStream mem = new MemoryStream(data);
MyPictureBox.Image = Image.FromStream(mem);
}
更多信息:
- the type in MySQL is
varbinary(8000)and contains this "89504e470d0a1a0a0000000d4948445200000280000001e00802000000bab34bb3000000017352474200aece1ce90000000467414d41002e2e2e" after theupdate - 图片在第一个
PictureBox加载时会转换为位图。
【问题讨论】:
-
图片一定要入库吗?
-
请阅读:stackoverflow.com/questions/815626/… 并且您的 IMG 应该是 BLOB 而不是 varbinary(8000),当您使用 BLOB 时,您可以将其存储为二进制数据,然后它将被检索为 byte[]跨度>
-
@ChesterCobus 它不必在数据库中,但我想要它。只是因为我想知道它是如何工作的
-
希望对您有所帮助:aspsnippets.com/Articles/…
-
@ChesterCobus 感谢您提到它在 BLOB 中!