【问题标题】:How can I store and retrieve an image using an SQLite database and a WPF application?如何使用 SQLite 数据库和 WPF 应用程序存储和检索图像?
【发布时间】:2010-12-21 06:44:53
【问题描述】:

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

【问题讨论】:

标签: c# wpf image sqlite


【解决方案1】:

我建议先将图片转成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;
  }
}

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;
}

您可以将字符串保存在数据库中。这个问题与之相关:How do i read a base64 image in WPF?

【讨论】:

  • 虽然会产生一些非常大的字符串
  • 这取决于图像的大小,但是是的,它会产生非常大的字符串。但是在某个地方有要存储的信息。
【解决方案2】:

为什么不存储图像相对于应用程序根目录的路径?

【讨论】:

  • 因为这不能实现将图像存储在数据库中的目标?您必须在磁盘上保留一个单独的图像文件才能使其正常工作,这显然不是提问者所希望的。
  • 这不是他的答案的解决方案,而是另一种选择。
猜你喜欢
  • 2015-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-17
  • 1970-01-01
  • 1970-01-01
  • 2011-09-24
  • 2015-08-01
相关资源
最近更新 更多