我无法从mysql blob获取图像。我尝试了以下代码,但它给了我这个错误:“连接必须有效且打开”。请注意,我正在使用WPF。 开放连接布尔:
public bool OpenConnection()
{
try
{
conn.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Neuspesna konekcija na server!");
break;
case 1045:
MessageBox.Show("Korisnicko ime i Lozinka za server su pogresno unete!");
break;
}
return false;
}
}
laodImg方法:这是问题所在,但我无法理解它的哪一部分...
public void LoadImg()
{
PocetnaStrana ps = new PocetnaStrana();
try
{
if (OpenConnection())
{
MySqlCommand cmd = new MySqlCommand("SELECT profPic FROM Korisnici WHERE id=4");
MySqlDataReader rdr1 = cmd.ExecuteReader();
while (rdr1.Read())
{
byte[] data = (byte[])rdr1[0]; // 0 is okay if you only selecting one column
//And use:
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
{
var imageSource = new BitmapImage();
imageSource.BeginInit();
imageSource.StreamSource = ms;
imageSource.CacheOption = BitmapCacheOption.OnLoad;
imageSource.EndInit();
// Assign the Source property of your image
ps.profPicBX.Source = imageSource;
rdr1.Close();
}
}
}
else
{
conn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("something is wrong: " + ex);
}
}