Chirag Gohil
Chirag Gohil

Reputation: 387

store and display image in sqlite in windows store app?

I have a form from which I want to store an image to my sqlite database and then i want it to be displayed at another page as grid background. I am making an windows store app so I am using xaml and c#. I want the stored image as my gridview background.

Upvotes: 1

Views: 1521

Answers (3)

Abhishek
Abhishek

Reputation: 995

You can store your Image to database with 2 ways-

  1. By converting image to byte[]
    1. convert Image to bytes[] and save it to sqlite Blob type parameter.
    2. get that Blob datatype and store again to byte[] and then convert to Image
  2. By converting image to base64 string
    1. Convert image to base64 string store to sqlite in varchar/varchar2 type
    2. get base64 string from sqlite db and convert to image

Upvotes: 1

Farhan Ghumra
Farhan Ghumra

Reputation: 15296

Base-64 is best encoding technique to store images in SQLite. Try the below given code. One method will give you base-64 encoded string of StorageFile & other one will return you BitmapImage object, which can be set as source of <Image />.

private async Task<BitmapImage> Base64StringToBitmap(string source)
{
    var ims = new InMemoryRandomAccessStream();
    var bytes = Convert.FromBase64String(source);
    var dataWriter = new DataWriter(ims);
    dataWriter.WriteBytes(bytes);
    await dataWriter.StoreAsync();
    ims.Seek(0);
    var img = new BitmapImage();
    img.SetSource(ims);
    return img;
}

private async Task<string> ConvertStorageFileToBase64String(StorageFile imageFile)
{
    var stream = await imageFile.OpenReadAsync();

    using (var dataReader = new DataReader(stream))
    {
        var bytes = new byte[stream.Size];
        await dataReader.LoadAsync((uint)stream.Size);
        dataReader.ReadBytes(bytes);

        return Convert.ToBase64String(bytes);
    }
} 

Upvotes: 1

Nicol&#225;s Loaiza
Nicol&#225;s Loaiza

Reputation: 1015

You can store it as a base64 encoded image, when you need to show it, you must to decode the image.

try reading this

Upvotes: 1

Related Questions