Forum Xamarin.Forms

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

How to load embedded image resource in PCL assembly?

RaviBhavnaniRaviBhavnani USMember, University
edited July 2014 in Xamarin.Forms

My PCL assembly (named "Foo.Bar") contains a folder "Images" which contains an image file "check_yellow_24.png" (build action = EmbeddedResource). I'm trying to set this image as the source of an Image control. The image control doesn't display the image, ostensibly because the resource is not found at run time. This is how I'm setting the image source:

imgSelected.Source = ImageSource.FromResource("Foo.Bar.Images.check_yellow_24.png");

I've read the document Working with Images and confirmed the image isn't found at run time by viewing the output of the following diagnostic code fragment. The only discovered embedded resources are the assembly's .xaml files.

// Display names of embedded resources
var assembly = typeof(SomeClassDefinedInTheAssembly).GetTypeInfo().Assembly;
foreach (var res in assembly.GetManifestResourceNames())  {
    System.Diagnostics.Debug.WriteLine(">>> " + res);
}

What do I need to do to successfully retrieve the embedded image resource for use by the containing assembly?

Best Answer

Answers

  • RaviBhavnaniRaviBhavnani USMember, University

    Yes, the Working with Images sample works perfectly.

    There's nothing unusual about my solution. It's a VS 2012 solution that contains 3 PCL projects and an Android main app. The projects contains a number of Pages, view models and services, all of which work fine.

    The sample displays the resource name "beach.jpg" in the diagnostic output. I tried moving my images to the root folder, but the images continue to not be found at run time.

    The only difference I notice is that my assembly name contains a period. I tried renaming the assembly from Foo.Bar to FooBar, but that caused the app to throw an FileNotFoundException from Mono saying "Foo.Bar" was not found. I thought that odd, since I did a clean rebuild and uninstalled the previous version of the app from Genymotion before redeploying.

    I'm going to create a brand new assembly with no period in the name and see if that helps.

  • RaviBhavnaniRaviBhavnani USMember, University

    @CraigDunn‌ Gah! The build action on the images had reverted to BundleResource. Everything worked fine when I set the build action to EmbeddedResource. (Goes in search of more coffee...)

    Sorry for wasting your cycles!

  • CraigDunnCraigDunn USXamarin Team Xamurai

    No problem - glad it's working now!

  • MattButlerMattButler USUniversity ✭✭

    I'm having some issues with Embedded Resources. I've had this issue since I've been working with X.F. Some will load, some will not. If the path changes none will load. For instance, if I go into the Working with Images project, turn on the embedded images class and run it, it works. If I create a directory in the WorkingWithImages PCL called img and move the beach.jpg file into that directory and then update the path in EmbeddedImages()

    embeddedImage.Source = ImageSource.FromResource("WorkingWithImages.img.beach.jpg");
    tried
    embeddedImage.Source = ImageSource.FromResource("img.beach.jpg");
    too

    No Workie...

    If I change it back to

    embeddedImage.Source = ImageSource.FromResource("beach.jpg");

    And leave the file in the img folder, it works. What am I missing?

  • MattButlerMattButler USUniversity ✭✭
    edited January 2015

    Found the solution, RTFM!

    Debugging Embedded Images
    Because it is sometimes difficult to understand why a particular image resource isn't being loaded, the following debug code can be added temporarily to an application to help confirm the resources are correctly configured. It will output all known resources embedded in the given assembly to the Console to help debug resource loading issues.
    
    using System.Reflection;
    // ...
    // NOTE: use for debugging, not in released app code!
    var assembly = typeof(EmbeddedImages).GetTypeInfo().Assembly;
    foreach (var res in assembly.GetManifestResourceNames()) 
        System.Diagnostics.Debug.WriteLine("found resource: " + res);
    

    http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/images/#Icons_and_splashscreens

    The issue was that a leasing '_' was being added to the directories of my images.

    found resource: Assembly.Images._1080.refresh.png

  • batmacibatmaci DEMember ✭✭✭✭✭
    edited February 2016

    @MattButler said:
    Found the solution, RTFM!

    Debugging Embedded Images
    Because it is sometimes difficult to understand why a particular image resource isn't being loaded, the following debug code can be added temporarily to an application to help confirm the resources are correctly configured. It will output all known resources embedded in the given assembly to the Console to help debug resource loading issues.
    
    using System.Reflection;
    // ...
    // NOTE: use for debugging, not in released app code!
    var assembly = typeof(EmbeddedImages).GetTypeInfo().Assembly;
    foreach (var res in assembly.GetManifestResourceNames()) 
        System.Diagnostics.Debug.WriteLine("found resource: " + res);
    

    http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/images/#Icons_and_splashscreens

    The issue was that a leasing '_' was being added to the directories of my images.

    found resource: Assembly.Images._1080.refresh.png

    where is this EmbeddedImages at this line is defined? my VS returns not defined? var assembly = typeof(EmbeddedImages)

    EDIT: opps, it was just any class name in the PCL project :)

  • dpedrinhadpedrinha DEMember ✭✭✭

    Can somebody please explain what the SomeClassDefinedInTheAssembly or EmbeddedImages are? All File use examples have this type but none of them explains what is it or what should I put there. Not even at Working with Files docs.

  • ahmedkhanahmedkhan USUniversity ✭✭

    I had a similar issue as @MattButler

    I had been using an embedded images folder in my Xamarin Froms (iOS & Android) solution's PCL project. -This originally worked fine, but halfway through the development of my project, on IOS I find that the embedded images in the PCL's 'images' folder are no longer loading and strangely they sometimes appear after the app has been active (working) for a few minutes...

    I tried the same debug code and all it shows is the the resources are being loaded correctly and that the file paths are correctly referenced.

    I'm switching back to using the platform specific resources folder to load any image now. QUITE FRUSTRATING !!!

    using System.Reflection;
    // ...
    // NOTE: use for debugging, not in released app code!
    var assembly = typeof(EmbeddedImages).GetTypeInfo().Assembly;
    foreach (var res in assembly.GetManifestResourceNames()) 
        System.Diagnostics.Debug.WriteLine("found resource: " + res);
    
  • ThomasBurkhartThomasBurkhart DEMember ✭✭✭✭

    It's imporant to know that the code that loads the image has to be in the same assembly as the images.

  • AllanChin.6924AllanChin.6924 USUniversity ✭✭✭

    Should this IMarkupExtension mechanism still work if the image resources are added to the PCL under a subfolder such as "Resources"? If so, how with they be referenced in XAML and C#?

    Thanks

  • NajimMullaNajimMulla USMember

    how can show 2 or more images in image control & click on image control open image from gallary in cross-platform (PLC) Application

  • FrancoisLouwFrancoisLouw USMember

    For images located in PCL, you need to set imagesource to imagesource.fromresource("path"), and the path should include the path from the namespace to the image. and build action on image should be set to embedded resource

  • TimoSchmidtTimoSchmidt DEMember ✭✭

    I use this:

    ImageSource =ImageSource.FromResource ( ImageNameFromResource("check.png"));
    

    And that's the helper function:

        private string ImageNameFromResource(string u)
        {
            var assembly = typeof(App).GetTypeInfo().Assembly;
            foreach (var res in assembly.GetManifestResourceNames())
            {
              //  System.Diagnostics.Debug.WriteLine("found resource: " + res);
                if (res.Contains(u))
                {
                    return res;
                }
            }
            return null;
        }
    
  • This will work guys

    In CS File

    [ContentProperty("Source")]
    public class ImageResourceExtension : IMarkupExtension
    {
    public string Source { get; set; }

        public ImageSource ProvideValue(System.IServiceProvider serviceProvider)
        {
            if (Source == null)
                throw new ArgumentNullException("No image set!");
    
            // get the current assembly
            var assembly = typeof(App).GetTypeInfo().Assembly;
    
            var imageSource = ImageSource.FromResource(Source, assembly);
    
            return imageSource;
        }
    
        object IMarkupExtension.ProvideValue(System.IServiceProvider serviceProvider)
        {
            throw new NotImplementedException();
        }
    
    }
    
  • thebigbothebigbo Member ✭✭

    @TimoSchmidt said:
    I use this:

    ImageSource =ImageSource.FromResource ( ImageNameFromResource("check.png"));
    

    And that's the helper function:

        private string ImageNameFromResource(string u)
        {
            var assembly = typeof(App).GetTypeInfo().Assembly;
            foreach (var res in assembly.GetManifestResourceNames())
            {
              //  System.Diagnostics.Debug.WriteLine("found resource: " + res);
                if (res.Contains(u))
                {
                    return res;
                }
            }
            return null;
        }
    

    Thanks for this, man!

  • Ashish_sharmaAshish_sharma INMember ✭✭✭

    Hello guy's this url is not work in image control
    http://moto.ihubcrm.com/storage/user/789f3ba0-599e-11e8-afe4-59bb91f885a6/WMPHtV4uTGIGa9V6XtYMdIFu1qk8dC5ti7OsLT10.jpeg

    but if i give another url in this control it show.
    What is wrong with this url i don't know ? please help for this things to get solve.

Sign In or Register to comment.