How to save and retrive image from sqlite

some1some1 Member ✭✭✭
edited May 3 in Xamarin.Android

I have used Xamarin Media Plugin for image upload and i want to save that image in Sqlite and retrieve it back from Sqlite. How can i do that ?
This is my Xaml code.

`
< StackLayout >

< Label Text="Name" />

                < Entry x:Name="EName"  HorizontalOptions="FillAndExpand"  />

                <Button x:Name="uploadButton" 

                Text="Upload Image"

                Clicked="UploadButton_Clicked" Grid.Row="4" Grid.Column="2"/>

            </Grid>

        </StackLayout>`

here i get image full path in stream and then i converted it into byte[].

` private async void UploadButton_Clicked(object sender, EventArgs e)

    {

        if (!CrossMedia.Current.IsPickPhotoSupported)

        {

            await DisplayAlert("Warning", "Picking  a photo is not supported", "OK");

            return;

        }

        var file = await CrossMedia.Current.PickPhotoAsync();

        if (file == null)

            return;

        imageToUpload.Source = ImageSource.FromStream(() => file.GetStream());

        var stream = file.GetStream();

        byte[] result;

        using (var streamReader = new MemoryStream())

        {

            stream.CopyTo(streamReader);

            result = streamReader.ToArray();

        }`

How can save it and retrieve that image from sqlite.

Answers

  • Amit_Malhi01Amit_Malhi01 Member ✭✭

    After getting the image as bytes[] in result. You can save the bytes directly into sqlite database by creating object and then just simply save the object in database.

    Example:

    public Class UserImage
    {
    public byte[] Image { get; set; }

    public UserImage(byte[] image)
    {
    this.Image = image;
    }
    }

    var xImage = new UserImage(result); // result = streamReader.ToArray();

    //Save to DB by
    conn.Insert(xImage );

    //Retreive from DB
    conn.Table().FirstOrDefault();

  • JarvanJarvan Member, Xamarin Team Xamurai

    The basic idea to store/fetch Image bitmaps in most of the DB is following,

    Store: Convert the Image bitmap into a Base64String and store it to SQLite.

    public static string Base64Encode(string plainText) {
      var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
      return System.Convert.ToBase64String(plainTextBytes);
    }
    

    Retrieve: Fetch the Base64String and convert that to Bitmap again.

    public static string Base64Decode(string base64EncodedData) {
      var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
      return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
    }
    
Sign In or Register to comment.