2010-12-21 62 views
2

我必须将图像从我的WPF应用程序存储到SQLite数据库,然后检索相同的图像并将其显示在应用程序中。我试图通过将图像转换为字节数组并将该字节数组作为BLOB存储到SQLite数据库来完成此操作,但这不起作用。有人能帮我吗?如何使用SQLite数据库和WPF应用程序存储和检索图像?

+0

可能的重复[如何在WPF中读取base64图像?](http://stackoverflow.com/questions/593388/how-do-i-read-a-base64-image-in-wpf) – 2010-12-21 07:06:40

回答

5

我建议先将图像转换为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?

+0

虽然 – weloytty 2010-12-21 07:25:20

+0

这将取决于你的图像的大小,但是,它会做出非常大的字符串。但某处有信息要存储。 – Christian 2010-12-21 08:12:24

0

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

+2

因为这不能完成将图像存储在数据库中的目标?你必须在磁盘上保存一个单独的映像文件才能工作,这显然不符合提问者的要求。 – 2010-12-21 07:15:15

+0

这不是他的答案,而是一个替代方案。 – SimoneF 2010-12-21 08:19:51

相关问题