ish1104
ish1104

Reputation: 421

How to upload and retrieve image using sqlite databse

My question is in Xamarin.Forms using the SQLite database can upload an image and retrieve it to the same place(like a profile picture).

I look through google but I couldn't find anything like this is this possible to do in xamarin.Forms using SQLite local database

Upvotes: 2

Views: 803

Answers (1)

Gianmarco Varriale
Gianmarco Varriale

Reputation: 163

Yes it's possible. Watch this little example:

Just convert your image to a byte array, you can use:

byte[] myimage = System.IO.File.ReadAllBytes("pathtoimage")

insert the image into your sql lite db:

public bool InsertMessage()
{

    SqliteCommand cmd = new SqliteCommand(con);

        cmd.CommandText = "INSERT INTO Images(Data) VALUES (@img)";
        cmd.Prepare();

        cmd.Parameters.Add("@img", DbType.Binary, myimage.Length);
        cmd.Parameters["@img"].Value = myimage;
        cmd.ExecuteNonQuery();

        con.Close();
}

to retrive the image and store it to a file:

 using(SqliteConnection con = new SqliteConnection(cs))
        {            
            con.Open();

            SqliteCommand cmd = new SqliteCommand(con);   
            cmd.CommandText = "SELECT Data FROM Images WHERE Id=1";
            byte[] data = (byte[]) cmd.ExecuteScalar();

            try
            {               
                if (data != null)
                { 
                    File.WriteAllBytes("woman2.jpg", data);
                    myimage = data
                } else 
                {
                    Console.WriteLine("Binary data not read");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }            

            con.Close();
        }

if you want save the image into a bitmap var:

ByteArrayInputStream inputStream = new ByteArrayInputStream(myimage);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

Upvotes: 3

Related Questions