如何使用SQLite数据库和WPF应用程序存储和检索图像?

dha*_*nya 3 c# sqlite wpf image

我必须将我的WPF应用程序中的图像存储到SQLite数据库,然后检索相同的图像并将其显示在应用程序中.我尝试通过将图像转换为字节数组并将该字节数组作为BLOB存储到SQLite数据库来实现这一点,但这不起作用.有人能帮我吗?

Chr*_*ian 6

我建议先将图像转换为base64字符串,然后将其存储在数据库中.

在C#中:

图像到Base64字符串

public string ImageToBase64(Image image, 
  System.Drawing.Imaging.ImageFormat format)
{
  using (MemoryStream ms = new MemoryStream())
  {
    // Convert Image to byte[]
    image.Save(ms, format);
    byte[] imageBytes = ms.ToArray();

    // Convert byte[] to Base64 String
    string base64String = Convert.ToBase64String(imageBytes);
    return base64String;
  }
}
Run Code Online (Sandbox Code Playgroud)

Base64字符串到图像

public Image Base64ToImage(string base64String)
{
  // Convert Base64 String to byte[]
  byte[] imageBytes = Convert.FromBase64String(base64String);
  MemoryStream ms = new MemoryStream(imageBytes, 0, 
    imageBytes.Length);

  // Convert byte[] to Image
  ms.Write(imageBytes, 0, imageBytes.Length);
  Image image = Image.FromStream(ms, true);
  return image;
}
Run Code Online (Sandbox Code Playgroud)

您可以将字符串保存在数据库中.这个问题与它有关:我如何在WPF中读取base64图像?