如何使用sqlite数据库上传和检索图像 [英] How to upload and retrieve image using sqlite databse
问题描述
我的问题在Xamarin中.使用SQLite数据库的表单可以上传图像并将其检索到相同的位置(例如个人资料图片).
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).
我通过google浏览,但是我找不到像这样的东西,这可以在使用SQLite本地数据库的xamarin.Forms中完成
I look through google but I couldn't find anything like this is this possible to do in xamarin.Forms using SQLite local database
推荐答案
是的.观看这个小例子:
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")
将图像插入到sql lite db中:
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);
这篇关于如何使用sqlite数据库上传和检索图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!