UIImage.FromFile sometimes returns null

jessejesse USMember

I am seeing strange behavior where UIImage.FromFile is sometimes unable to locate an image in my app bundle. If I call this function from certain places in my code (for example ViewDidAppear of my main view controller) it correctly loads my image. If I call it anywhere else (for example ViewDidAppear of a view controller that I present later) it returns null, even though I'm calling it with the same image path.

Can anyone think of reasons this may be happening? I've tried the following, with no change in behavior:

  • making sure the calls are happening in the UI thread
  • using simulator and device
  • including images in the project as Content and as BundleResource
  • making sure the calling code is in the same project as the one that includes the images
  • trying different PNG images

I've tried the same thing from a simple test app created from scratch but it always works fine. But I haven't been able to figure out what's different about my production app.

My current workaround is to include images as EmbeddedResources and load them using NSData and GetManifestResourceStream, but that's not an ideal solution.

Best Answer

Answers

  • jessejesse USMember

    I will see if I can narrow it down to a bug report.

  • jessejesse USMember

    It turns out my code was changing the app's current directory (via Directory.SetCurrentDirectory(path)). After doing this, we can no longer load images by relative path (UIImage.FromFile("Images/MyImage.png")).

    Do you consider this to be a bug or expected behavior?

  • tohweitohwei USMember ✭✭

    UIImage.FromFile()
    I have recently converted an iOS project to 32/64 bits (unified api).

    I have this line of code to load images by relative path.
    var imgFile = UIImage.FromFile("Images/bg_splash_start_640x1136.png");

    I have no issue with this code at all before I've converted them to unified api.

    The problem that I am facing now is that the above line working fine in simulator (of iPhone 5, 5s, 6), but not on actual device, which is iPhone 5s. I got NULL for the imgFile.

    Build Action for the image file: BundleResources

    Just wondering,. does the UIImage.FromFile() no longer support?

  • I also had this problem on phone itself (the simulator worked fine). The most popular solutions had little effect, but I did see a comment about the compiler identifying resources to package up. I finally found that something like UIImage.FromFile(this.properties.MyImagePath) did not work (where the compiler optimiser might struggle to identify the image that needs shipping??), but that if I hard-coded the path like UIImage.FromFile("MyImage.png") the image was loaded. Note that I did validate the two values were the identical.

    I am not a Xamarin expert and there is some conjecture in this reply but hope it might help someone.

Sign In or Register to comment.