如何将选取的图像绑定到本地SQLite数据库,并显示在不同于Media picker按钮所在页面的页面上? XAMARIN

How to bind picked images to the local SQLite database and display them on the page different from the page where Media picker buttons are? XAMARIN

嗨,Xamarin 众神和女神们。我正在尝试找到绑定使用媒体选择器(捕获照片)和媒体库(选择照片)选择的图像的解决方案,以便将它们保存在本地 SQLite 数据库中并稍后在列表视图中显示它们。 我有两个按钮事件处理程序,用于从相机拍摄照片和从图库中挑选照片。它们都是相似的方法(另外,这两种方法是否有更好的方法来避免流?)。但是,我不确定如何绑定它们的结果并将它们显示在我的列表视图和 SQLite 数据库中。页面上有一个保存按钮,可以保存用户所做的所有输入,例如标题、体验、位置和图像(我正在纠结,如何保存图像?)。单击保存按钮时,更改将显示在列表视图和 SQLite 中。 对于文本输入来说很容易做到这一点。但是,如何为图像做这件事????我认为它应该以某种方式转换为字节和数组。但是怎么办?请帮忙!!!! 下面是我的代码和提到的方法以及我如何将它显示到列表视图。 所以基本上,我想要做的是让用户在体验、标题、位置和图像方面输入。在我的模型里有Postclass,保存到SQ里显示在列表视图里

XAML.CS

 namespace GetAroundCroatia
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class IznajmiIznajmljivaciPage1 : ContentPage
    {
        public IznajmiIznajmljivaciPage1()
        {
            InitializeComponent();
        }
  private async void takePhoto_Clicked(object sender, EventArgs e)
        {
            var photo = await MediaPicker.CapturePhotoAsync();
            if (photo != null)
            {                
            var stream = await photo.OpenReadAsync();
            resultImage.Source = ImageSource.FromStream(() => stream);          
            }     
        }      
        private async void pickPhotos_Clicked(object sender, EventArgs e)
        {
            var results = await MediaGallery.PickAsync(3, MediaFileType.Image);
            if(results != null)
            {
                var imageList = new List<ImageSource>();
                foreach (var media in results.Files)
                {
                    var stream = await media.OpenReadAsync();
                    imageList.Add(ImageSource.FromStream(() => stream));
                }
                collectionView.ItemsSource = imageList;
            }     
        }
        private void save_Clicked(object sender, EventArgs e)
        {
            try
            {          
            PostClass post = new PostClass()
            {
                Experience = experienceEntry.Text,
                Title = titleEntry.Text,
                Location = locationEntry.Text,                                  
            };
            using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
            {
                conn.CreateTable<PostClass>();
                int rows = conn.Insert(post);                    
                if (rows > 0)
                    DisplayAlert("Uspjesno", "Oglas Predan", "OK");
                else
                    DisplayAlert("Neuspjesno", "Oglas nije predan", "OK");
            }

            }
            catch (NullReferenceException nre)
            {
            }
            catch(Exception ex)
            {
            }
        }
    }

XAML:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="GetAroundCroatia.IznajmiIznajmljivaciPage1">
    <ContentPage.ToolbarItems>
        <ToolbarItem x:Name="Save" Text="Predaj" Clicked="save_Clicked"/>        
    </ContentPage.ToolbarItems>    
    <ContentPage.Content>
        <ScrollView>
            <StackLayout>                
                <Button x:Name="takePhoto" Text="Uslikaj" Clicked="takePhoto_Clicked"/>
                <Image x:Name="resultImage"/>                
                <Button x:Name="pickPhotos" Text="Odaberi iz galerije" Clicked="pickPhotos_Clicked"/>               
                <CollectionView x:Name="collectionView">
                    <CollectionView.ItemTemplate>
                        <DataTemplate>
                            <Image Source="{Binding .}" />
                        </DataTemplate>
                    </CollectionView.ItemTemplate>
                </CollectionView>
                <Label Text="Opci Podaci"/>
                <Entry x:Name="titleEntry"
                       Placeholder="Title"/>     
                <Entry x:Name="experienceEntry"
                       Placeholder="Opis"/>
                <Entry x:Name="locationEntry"
                       Placeholder="Unesi Lokaciju"/>
                <Entry x:Name="raspolozivostEntry"
                       Placeholder="Odaberi Raspolozivost"/>
                <Entry x:Name="dostavaEntry"
                       Placeholder="mogucnost dostave"/>           
                <Entry x:Name="soferopcijaEntry"
                       Placeholder="Mogucnost Vozac" />
            </StackLayout>
        </ScrollView>      
    </ContentPage.Content>
</ContentPage>

型号POSTCLASS:

public class PostClass
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
        [MaxLength(300)]
    public string Experience { get; set; }
        public string Title { get; set; }
        public string Location { get; set; }
    }

列表视图XAML:

<ListView x:Name="PostListViewOglasi"
                  ItemTapped="PostListViewOglasi_ItemTapped">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand">
                            <Label Text="{Binding Title}" FontSize="15"/>
                            <Label Text="{Binding Experience}" FontSize="15"/>
                            <Label Text="{Binding Location}" FontSize="15"/>  
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

列表视图XAML.CS:

 public OglasiListViewPage1()
        {
            InitializeComponent();
        }
        protected override void OnAppearing()
        {
            base.OnAppearing();
            using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation)) 
            {
                conn.CreateTable<PostClass>();
                var posts = conn.Table<PostClass>().ToList();
                PostListViewOglasi.ItemsSource = posts;
            }
        }
        private void PostListViewOglasi_ItemTapped(object sender, ItemTappedEventArgs e)
        {
            var selectedPost = PostListViewOglasi.SelectedItem as PostClass;
            if(selectedPost != null)
            {
                Navigation.PushAsync(new DetaljiPostOglasaPage1(selectedPost));
            }
        }
    }

Media Picker (capture photo) and Media Gallery (pick photos)

你在你的项目中使用了什么nuget?

并且建议您使用Xamarin.Essentials: Media Picker来实现。

您可以在拍摄图像后获取图像的 FullPath,但 stream 除外。

请参考以下代码:

async void CapturePhoto_Clicked(System.Object sender, System.EventArgs e)
    {
        var result = await MediaPicker.CapturePhotoAsync();

        if (result != null)
        {
            var stream = await result.OpenReadAsync();

            resultImage.Source = ImageSource.FromStream(() => stream);

            string imagePath = result.FullPath;// get the fullpath and save to database
        }
    }

要将图像保存到数据库,您只需添加一个新的 属性,例如:

  public string imagePath { get; set; }` 

到您的 class PostClass 并将 imagePath 保存到您的数据库。

您也可以使用方法 MediaPicker.PickPhotoAsync选择照片。

请参考以下代码:

    async void Button_Clicked(System.Object sender, System.EventArgs e)
    {
        var result = await MediaPicker.PickPhotoAsync(new MediaPickerOptions
        {
            Title = "Please pick a photo"
        });

        if (result != null)
        {
            var stream = await result.OpenReadAsync();

            resultImage.Source = ImageSource.FromStream(() => stream);

            string path = result.FullPath;
        }
    }

注:

How to bind picked images to the local SQLite database and display them on the page different from the page

如何从数据库中加载图片,可以参考以下线程: .

感谢@Jessie Zhang 和@Jason,我找到了解决方案。因此,我将它与可能遇到类似问题的其他人分享。我在捕获照片方法之外声明了 imagePath 字符串,并在我的捕获照片方法和我的保存按钮方法中访问它。下面是我如何捕获照片、将其保存在本地 SQLite 中并在我的列表视图中显示的完整代码。谢谢大家的帮助。

public partial class IznajmiIznajmljivaciPage1 : ContentPage
{
    public IznajmiIznajmljivaciPage1()
    {
        InitializeComponent();
    }
    string imagePath;
    private async void takePhoto_Clicked(object sender, EventArgs e)
    {
        var photo = await MediaPicker.CapturePhotoAsync();

        if (photo != null)
        {
            
        var stream = await photo.OpenReadAsync();

        resultImage.Source = ImageSource.FromStream(() => stream);
            imagePath = photo.FullPath;
        }
    }

private void save_Clicked(object sender, EventArgs e)
    {
        try
        {

        
        PostClass post = new PostClass()
        {
            Experience = experienceEntry.Text,
            Title = titleEntry.Text,
            Location = locationEntry.Text,
            imagePath = imagePath
            };


        using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
        {
            conn.CreateTable<PostClass>();
            int rows = conn.Insert(post);
                

            if (rows > 0)
                DisplayAlert("Uspjesno", "Oglas Predan", "OK");
            else
                DisplayAlert("Neuspjesno", "Oglas nije predan", "OK");
        }

        }
        catch (NullReferenceException nre)
        {

        }
        catch(Exception ex)
        {

        }

POST CLASS:

 public string imagePath { get; set; }

列表视图:

 <Image Source="{Binding imagePath}"/>