5

I have to store an image from my WPF application to the SQLite database, and then retrieve the same image and display it in the application. I tried doing this by coverting the image into byte array and storing that byte array to the SQLite database as BLOB, but this is not working. Can someone help me?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
dhanya
  • 61
  • 1
  • 3

2 Answers2

5

I would suggest to convert the image to a base64 string first and then store it in the database.

In C#:

Image to Base64 String

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 String to Image

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

You can save the string in the database. This question is related to it: How do i read a base64 image in WPF?

Community
  • 1
  • 1
Christian
  • 3,503
  • 1
  • 26
  • 47
1

Why don't you store the path to the image relative to the application's root?

SimoneF
  • 432
  • 1
  • 3
  • 15
  • 5
    Because that doesn't accomplish the goal of storing the image in a database? You have to keep a separate image file on disk for this to work, which is apparently not what the asker wishes. – Cody Gray - on strike Dec 21 '10 at 07:15
  • 1
    It is not a solution to his answer, but an alternative. – SimoneF Dec 21 '10 at 08:19