我正在创建WPF应用程序,在其中我需要将个人资料图片保存到mysql数据库中。我成功保存了图像,但是由于某种原因,我认为它不好,因为我保存的任何图片始终都存在“ BLOB-13B”,因此我保存的任何大小都得到了该Blob大小。另一件事是,当我想从数据库加载图像时,它根本不会加载。看我的代码,第一个是saveImg方法:
public bool saveImg(string img)
{
FileStream fs;
BinaryReader br;
byte[] ImageData;
fs = new FileStream(img, FileMode.Open, FileAccess.Read);
br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
string query = $"UPDATE Korisnici SET profPic = '{ImageData}' WHERE id = 4;";
try
{
if (OpenConnection())
{
MySqlCommand cmd = new MySqlCommand(query, conn);
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Slika sacuvana!");
return true;
}
catch (Exception ex)
{
return false;
}
}
else
{
conn.Close();
return false;
}
}
catch (Exception)
{
conn.Close();
return false;
}
}
,第二个是LoadPic方法,我在其中显示图像并同时保存它。这是我点击按钮时要调用的方法。
private void loadPicture()
{
string img;
OpenFileDialog op = new OpenFileDialog();
op.Title = "Select a picture";
op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
"JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
"Portable Network Graphic (*.png)|*.png";
if (op.ShowDialog() == true)
{
profPicBX.Source = new BitmapImage(new Uri(op.FileName));
img = op.FileName.ToString();
dc.saveImg(img);
}
}
这是loadImg方法:
public void LoadImg()
{
PocetnaStrana ps = new PocetnaStrana();
try
{
if (OpenConnection())
{
try
{
MySqlCommand cmd = new MySqlCommand("SELECT profPic FROM Korisnici WHERE id = 4;");
MySqlDataReader rdr1 = cmd.ExecuteReader();
while (rdr1.Read())
{
byte[] data = (byte[])rdr1[0];
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;
}
}
}
catch (Exception ex)
{
}
}
else
{
conn.Close();
}
}
catch (Exception)
{
conn.Close();
}
}
我不知道我在哪里弄错了..?