Kanwaljeet Mehta
Kanwaljeet Mehta

Reputation: 73

Image not displaying from Image Path .Net Maui

I am trying to display image in a collection view. Image is saved to the Applicationdatadirectory using MediaPicker.Default.CapturePhotoAsync(); Once the image is captured I am saving the image path to sqlite db. And on the collection view I am trying to display the image from that path.

Here is the XAML code

                <Frame HeightRequest="70">
                    <Grid ColumnDefinitions="Auto, *">
                        <Grid Grid.Column="0">
                            <Image Source="{Binding Img_Front_Left}" Aspect="AspectFill"  WidthRequest="70" HeightRequest="70" >
                                
                            </Image>
                        </Grid>
                        <Grid Grid.Column="1">
                            <HorizontalStackLayout>
                                <Label Text="{Binding Model}"></Label>
                                <Label Text="{Binding StockNumber}"></Label>
                            </HorizontalStackLayout>
                        </Grid>
                    </Grid>
                </Frame>

            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>
    
</RefreshView>

But Instead of displaying the image it displays the image path. Any help is appreciated.

Here is the code that saves the image.

FileResult carPic_Front_Left = await MediaPicker.Default.CapturePhotoAsync();
if (carPic_Front_Left != null)
{
    string carPic_Front_Left_Path = Path.Combine(FileSystem.Current.AppDataDirectory, barcode.Text.ToString()+"_front_left.jpg");
    using Stream carPic_Front_Left_stream = await carPic_Front_Left.OpenReadAsync();
    using FileStream carPic_Front_Left_FileStream = File.OpenWrite(carPic_Front_Left_Path);
    await carPic_Front_Left_stream.CopyToAsync(carPic_Front_Left_FileStream);                    
    frontLeft.Source = carPic_Front_Left_FileStream.Name;
}

Upvotes: 0

Views: 1322

Answers (1)

Jessie Zhang -MSFT
Jessie Zhang -MSFT

Reputation: 13889

I can't see other details of your code, but I achieved this function on my side.

You can refer to the following code:

1.create a view model for this page (MyViewModel.cs)

public class MyViewModel: INotifyPropertyChanged
    {
        public ObservableCollection<Item> Items { get; set; }
        public ICommand CapturePhotoCommand { get; }


        string photoPath;
        public string PhotoPath
        {
            get => photoPath;
            set => SetProperty(ref photoPath, value);
        }

        public MyViewModel() {
            CapturePhotoCommand = new Command(DoCapturePhoto, () => MediaPicker.IsCaptureSupported);

            Items = new ObservableCollection<Item>();
        }

        async void DoCapturePhoto()
        {
            try
            {
                var photo = await MediaPicker.CapturePhotoAsync();

                await LoadPhotoAsync(photo);

                Console.WriteLine($"CapturePhotoAsync COMPLETED: {PhotoPath}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"CapturePhotoAsync THREW: {ex.Message}");
            }
        }

        async Task LoadPhotoAsync(FileResult photo)
        {
            // canceled
            if (photo == null)
            {
                PhotoPath = null;
                return;
            }

            // save the file into local storage
            var newFile = Path.Combine(FileSystem.CacheDirectory, photo.FileName);
            using (var stream = await photo.OpenReadAsync())
            using (var newStream = File.OpenWrite(newFile))
            {
                await stream.CopyToAsync(newStream);
            }

            PhotoPath = newFile;

            //jessie
            Items.Add(new Item { ImgPath = newFile });
            System.Diagnostics.Debug.WriteLine("----------> " + PhotoPath);


        }


        bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
        {
            if (Object.Equals(storage, value))
                return false;
            storage = value;
            OnPropertyChanged(propertyName);
            return true;
        }
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }

    public class Item
{
    public string ImgPath { get; set; }
    public string Name { get; set; }
}

2.On MainPage.xaml,I added a Button to take phone, and after capturing the image, the image will been display on the ListView of this page.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:controls="clr-namespace:MauiApp120123.Controls"
             xmlns:viewmodels="clr-namespace:MauiApp120123.ViewModels"
             x:Class="MauiApp120123.MainPage">

    <ContentPage.BindingContext>
        <viewmodels:MyViewModel></viewmodels:MyViewModel>
    </ContentPage.BindingContext>

    <VerticalStackLayout>
        <ListView ItemsSource="{Binding Items}" HasUnevenRows="True"   >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <HorizontalStackLayout >
                            <Image Source="{Binding ImgPath}"  WidthRequest="60" HeightRequest="60" BackgroundColor="Pink"/>
                            <Label Text="imageName" />
                        </HorizontalStackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

        <Button Text="Capture photo"
                Command="{Binding CapturePhotoCommand}"  IsVisible="true"/>  

    </VerticalStackLayout>

</ContentPage>

Note:

From document Media picker for photos and videos,we should add the platform-specific set up for our app.

Upvotes: 1

Related Questions