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

标签 c# sqlite xamarin.forms

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

我浏览了谷歌,但我找不到类似的东西,这是否可以使用 SQLite 本地数据库在 xamarin.Forms 中完成

最佳答案

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

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

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

将图像插入到您的 sql lite 数据库中:

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

关于c# - 如何使用sqlite数据库上传和检索图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54920728/

相关文章:

c# - 限制数据查询,只获取最后 1000 行

c# - 将单个 WPF 控件绑定(bind)到多个项目

C# LINQ 求和数组属性

python - 更改子类模型表中的列顺序

xaml - Xamarin 表单(跨平台): Multiple type of cells in ListView

c# - 转换RGB方法?

带复选框的 Android ListView

php - 成功登录后如何将用户重定向到新的 PHP 页面?

android - 无法在 Android 平台上初始化 ZXing - Xamarin Forms 应用程序

app-store - xamarin.forms从App Store/Google Store读取应用程序版本