如何使用sqlite数据库上传和检索图像

时间:2019-02-28 07:46:05

标签: c# sqlite xamarin.forms

我的问题在Xamarin中。使用SQLite数据库的表单可以上传图像并将其检索到同一位置(例如个人资料图片)

我翻查过google,但找不到类似的东西,这可以在xamarin.Forms中使用SQLite本地数据库完成

1 个答案:

答案 0 :(得分:1)

是的,有可能。观看这个小例子:

只需将图像转换为字节数组,即可使用:

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

将图像插入到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();
}

检索图像并将其存储到文件中

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

如果要将图像保存到位图变量中:

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