我必须将我的WPF应用程序中的图像存储到SQLite数据库,然后检索相同的图像并将其显示在应用程序中。我尝试将图像转换为字节数组并将该字节数组作为BLOB存储到SQLite数据库中,但这不起作用。有人能帮助我吗?
答案 0 :(得分: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;
}
}
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?
答案 1 :(得分:0)
为什么不存储相对于应用程序根目录的图像路径?