如何在 Xamarin Forms 的 SQLite 中保存图像? [英] How to save an image in SQLite in Xamarin Forms?

查看:20
本文介绍了如何在 Xamarin Forms 的 SQLite 中保存图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两种方法来处理从相机拍摄照片和从库中挑选照片.它们都是类似的方法,在每个方法的末尾,我从 Stream 返回一个 ImageSource 并将其传递到另一个具有 ImageSource 的页面上 绑定准备好设置.这两种方法效果很好.现在下一步是将图像保存在 SQLite 中,以便稍后我可以在 ListView 中显示图像.我对 XamGods 的问题(Xamarin Pros =),2019 年在 SQLite 中保存图像的最佳方法是什么?我已经在论坛上待了几个小时,但我仍然对我想做的事情没有明确的看法.我也可以

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 get an ImageSource back from the Stream and I pass it onto another page which has an ImageSource binding ready to be set. These two method work perfectly. The next step now is to save the Image in SQLite so I can show the images in a ListView later on. My question for the XamGods (Xamarin Pros =), what is the best way to save image in SQLite in 2019? I have been in the forums for hours and I still don't have a tunnel vision on what I want to do. I can either

  • 将 Stream 转换为字节数组以保存在 Sqlite 中.
  • 将 ImageSource 转换为字节数组(混乱/错误).
  • 以某种方式检索选择/拍摄的实际图像并将其转换为字节数组到 SQLite

如果我的问题是一般性的,我很抱歉,但 Xamarin 没有提供关于如何在 SQLite 中保存图像的明确解决方案,您只能在下面列出的论坛中找到零碎的解决方案.

I'm sorry if my question is general, but Xamarin does not provide a clear-cut solution on how to save images in SQLite and you can only find bits and pieces of solutions throughout the forums listed below.

先谢谢你!

    private async Task OnAddPhotoFromCameraSelected()
    {
        Console.WriteLine("OnAddPhotoFromCameraSelected");

        var photo = await Plugin.Media.CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions() { });
        var stream = photo.GetStream();
        photo.Dispose();
        if (stream != null)
        {
            ImageSource cameraPhotoImage = ImageSource.FromStream(() => stream);
            var parms = new NavigationParameters();
            parms.Add("image", cameraPhotoImage);
            var result = await NavigationService.NavigateAsync("/AddInspectionPhotoPage?", parameters: parms);

            if (!result.Success)
            {
                throw result.Exception;
            }
        }
    }

    private async Task OnAddPhotoFromLibrarySelected()
    {
        Console.WriteLine("OnAddPhotoFromLibrarySelected");
        Stream stream = await DependencyService.Get<IPhotoPickerService>().GetImageStreamAsync();
        if (stream != null)
        {
            ImageSource selectedImage = ImageSource.FromStream(() => stream);

            var parms = new NavigationParameters();
            parms.Add("image", selectedImage);
            parms.Add("stream", stream);
            var result = await NavigationService.NavigateAsync("/AddInspectionPhotoPage?", parameters: parms);

            if (!result.Success)
            {
                throw result.Exception;
            }
        }
    }

推荐答案

正如 Jason 所说,可以将图像路径保存到 sqlite 数据库中,但是如果您仍然想将 byte[] 保存到 sqlite 数据库中,则需要将 stream 转换为byte[] 首先:

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

然后从 sqlite 加载 byte[],转换成流.

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

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

对于简单的示例,您可以查看:在 sqlite 中插入 byte[]:

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

从 sqlite 加载图像:

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

        }
    }

型号:

public class Image
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string FileName { get; set; }   
    public byte[] Content { get; set; }
}

这篇关于如何在 Xamarin Forms 的 SQLite 中保存图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆