Forum Xamarin.Forms

How to load images from local path in Xamarin.Forms

zlazozlazo PEMember ✭✭

In my app I download images using dependency service into platform tmp app (in ios, going to implement android version latter), then I load try to show the downloaded images but the If i Bind the image path to a Image control in xaml it never shows the image. By the way im storing a partial path to the image and at runtime i get the full path, the flow is like this:

  1. Download image with dependency service using NSUrlSession.
  2. Move the image to /Caches/ directory in my app root.
  3. Save that partial path like "/Caches/img1.jpg" in a db
  4. Load a view at my app and get the image from the db.
  5. Build the full image path like "file:///Users/mbuild/Library/Developer/CoreSimulator/Devices/BF78E8FE-16D2-4F85-9C64-E8DCC98848F6/data/Containers/Data/Application/570C1598-6EBC-40CC-833E-50478E70FD7C/Library/Caches/53d09f9f-531d-4412-87cb-41a26d986e4e-1513113235590-img_0151.jpg" I try with and without "file://" also try it on a device because this is a simulator path.
  6. Use that path like a viewmodel string property like "ImgSrc"
  7. Bind the property to a Image control in several ways like:

<Image Source="{Binding ImgSrc}" /> OR <Image HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Aspect="AspectFit"> <Image.Source> <FileImageSource File="{Binding ImgSrc}" /> </Image.Source> </Image>

I dont know what im doing wrong
Any Ideas?

Tagged:

Best Answers

Answers

  • zlazozlazo PEMember ✭✭

    Thanks for the quick response actually I was generating a bad path to the image it loads without the converter but implement the actual converter like you did, show me the error thanks a lot :)

  • MichaelKayMichaelKay GBMember ✭✭

    @zlazo could you kindly provide an example how you're calling this converter class. I'm having exact issue when trying to load an image that was saved using a PCLStorage in iOS.

    What i don't get is, looking at solution provided by @Bohir, where are you passing the file path of the image - is there a model? In my solution i'm not using a model. I just have a simple cached image like

    var image = new CachedImage(); image.Source = ImageSource.FromFile(<FilePath>);

    I'm guessing to use above i need to do something like below - but i have no idea how to do this and reference the local file path:
    Binding binding = new Binding(<set params>);
    image.SetBinding(Image.SourceProperty, binding);

    Any help will be much appriciated

    Thanks

  • MichaelKayMichaelKay GBMember ✭✭
    edited August 2018

    I solved this myself. I achieved this through binding using a view model. I'm guessing this wouldn't be much of an issue on physical devices - I don't have an iOS physical device to test at hand currently. But current solution works a beauty.

    Because I was using PCLStorage, my converter looks like this:

    `public class ImageFileToImageSourceConverter: IValueConverter

    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
    
            string filename = (string)value;
    
            IFolder folder = FileSystem.Current.LocalStorage;
            folder = folder.GetFolderAsync("media").Result;
            IFolder productFolder = folder.GetFolderAsync("products").Result;
    
            ExistenceCheckResult exists = productFolder.CheckExistsAsync(filename).Result;
            var check = productFolder.GetFilesAsync().Result;
    
            if (exists == ExistenceCheckResult.FileExists)
            {
                IFile file = productFolder.GetFileAsync(filename).Result;
    
                return ImageSource.FromUri(new Uri(file.Path));
            }
    
            return null;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
    }`
    

    Thanks to this link for the above pointer: https://forums.xamarin.com/discussion/123664/ffimageloading-not-showing-images-from-localstorage-in-ios

    My view model looks like this:

    `public class TestImageViewModel : ObservableObject

    {
        string fileName = string.Empty;
    
        public string ImageFileName
        {
            get { return fileName; }
            set { SetProperty(ref fileName, value); }
        }
    }`
    

    Then on the content page, this is the bit that throws me, where are you passing the file path/file name? Now I know, I can do this when binding my context to the view model:

    this.BindingContext = new TestImageViewModel() { ImageFileName = "<File name is here>"; };

    And then simply bind this to the image, in my solution I'm using FFImageLoading:

    _image = new CachedImage(); _image.CacheDuration = TimeSpan.FromDays(0); _image.SetBinding(CachedImage.SourceProperty, "ImageFileName", converter: new ImageFileToImageSourceConverter());

    Seems confusing at first glance but straightforward once you get hang of it. Plus most example I saw online shows the binding mainly through xaml. Hope this help someone else who may stumble on this.

    Cheers

  • hermannhermann USMember ✭✭

    I try to load the image from Xamarin.Essentials.FileSystem.AppDataDirectory with a converter like

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var file = (string)value;
        var path = Path.Combine(FileSystem.AppDataDirectory, file);
        var src1 = ImageSource.FromFile(path); // DOES NOT WORK 
        // results in: src1 = {File: /data/user/0/com.company.App/files/image_solution.jpg}
    
        var src2 = ImageSource.FromUri(new Uri(path)); // DOES NOT WORK EITHER
            // results in: src2 = {Uri: file:///data/user/0/com.company.App/files/image_solution.jpg}
    
        return src2; // src1;
    }
    

    The converter is called in a xaml like

    <Image Source="{Binding Filename, Converter={StaticResource AppDataImage}}"/>
    

    What do I do wrong???

  • alexleo_341alexleo_341 Member ✭✭
    edited September 2019

    how to used this, it marks me error in converters

    "<ContentPage.Resources>



    </ContentPage.Resources>"

Sign In or Register to comment.