0

I have a series of images stored online which I try to reach programmatically in my Universal Windows Phone App. Is there a way to find out if the Image exists for the selected parameter and, if not, use an Image placeholder instead?

var img = new BitmapImage(new Uri("url?ID_IMMAGINE=" + idImg1 + "&HEIGHT=100", UriKind.Absolute))

this is how I get the image.

Janinho67
  • 145
  • 6
  • 17

2 Answers2

2

You could attach a handler for the ImageFailed event to set a fallback value for the URI:

var defaultImageUri = new Uri("ms-appx:///Assets/DefaultImage.png");
var bitmap = new BitmapImage();
bitmap.ImageFailed += (s, e) => bitmap.UriSource = defaultImageUri;
bitmap.UriSource = new Uri(...);
Clemens
  • 123,504
  • 12
  • 155
  • 268
  • When I try to use this I get the following exception: the application called an interface that was marshalled for a different thread. (exception from hresult: 0x8001010e (rpc_e_wrong_thread)) ... Do you know how I can fix this? The exception is thrown when I'm trying to create a new instance of BitmapImage() – Dennis Schröer Sep 15 '16 at 08:16
  • @Zure Better ask a regular StackOverflow question instead of asking in a comment. – Clemens Sep 15 '16 at 08:21
0

You cant use async for Converter. return type of async method must be void,Task,Task<T>. That cant be given to Convert method

           try
            {
                var img = new BitmapImage(new Uri("url?ID_IMMAGINE=" + idImg1 + "&HEIGHT=100", UriKind.Absolute));
                if (img == null)
                {
                    img = new BitmapImage(new Uri("defaultImage.png",UriKind.RelativeOrAbsolute));
                }
            }
            catch
            {
                img = new BitmapImage(new Uri("defaultImage.png", UriKind.RelativeOrAbsolute));
            }

If you really want to use converter please go through this Stackoverflow link

Community
  • 1
  • 1
Archana
  • 3,213
  • 1
  • 15
  • 21
  • Except that `new BitmapImage(...)` neither returns null nor throws an exception when the image can't be downloaded. – Clemens Apr 15 '16 at 10:51
  • If the given URL doesnt exist it throws the exception. – Archana Apr 15 '16 at 10:53
  • No it doesn't. Just give it a try. – Clemens Apr 15 '16 at 10:54
  • And your code won't compile because you have declared `img` inside the try block but also access it in the catch block. – Clemens Apr 15 '16 at 10:56
  • Yes i agree. should have written outside. I dint run the code and see. According to the documentation if the file name specified in uriString is not valid it throws UriFormatException. Again i dint run the sample and checked – Archana Apr 15 '16 at 10:59
  • UriFormatException is throw when the URI isn't properly formatted. The question is not about that, but about a valid URI pointing to a non-existing resource. – Clemens Apr 15 '16 at 11:01