How to save an image in SQLite in Xamarin Forms?

前端 未结 1 1387
既然无缘
既然无缘 2021-01-16 08:57

I have the following two methods that handles taking photos from a camera and picking photos from a library. They\'re both similar methods as at the end of each method, I ge

相关标签:
1条回答
  • 2021-01-16 09:32

    As Jason said that you can save image path into sqlite database, but if you still want to save byte[] into sqlite database, you need to convert stream into byte[] firstly:

     private byte[] GetImageBytes(Stream stream)
        {
            byte[] ImageBytes;
            using (var memoryStream = new System.IO.MemoryStream())
            {              
                stream.CopyTo(memoryStream);             
                ImageBytes = memoryStream.ToArray();
            }
            return ImageBytes;
        }
    

    Then load byte[] from sqlite, converting into stream.

     public Stream BytesToStream(byte[] bytes)
        {
            Stream stream = new MemoryStream(bytes);
            return stream;
        }
    

    For simple sample, you can take a look: Insert byte[] in sqlite:

     private void insertdata()
        {
            var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "sqlite1.db3");
            using (var con = new SQLiteConnection(path))
            {
                Image image = new Image();
                image.Content = ConvertStreamtoByte();
                var result = con.Insert(image);
    
                sl.Children.Add(new Label() { Text = result > 0 ? "insert successful insert" : "fail insert" });
            }
        }
    

    Loading image from sqlite:

     private void getdata()
        {
            var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "sqlite1.db3");
            using (var con = new SQLiteConnection(path))
            {
                var image= con.Query<Image>("SELECT content FROM Image ;").FirstOrDefault();
    
                if(image!=null)
                {
                    byte[] b = image.Content;
                    Stream ms = new MemoryStream(b);
                    image1.Source = ImageSource.FromStream(() => ms);                   
                }
    
            }
        }
    

    Model:

    public class Image
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
        public string FileName { get; set; }   
        public byte[] Content { get; set; }
    }
    
    0 讨论(0)
提交回复
热议问题