Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Forms: Default Image if Url not found

In xamarin forms we can create images like this:

Image i = new Image { Source = "http://www.foo.com/foo.jpg };

After adding this to layout if url returns an image it will display it. What I want to now is is there a way to know if ths Url is an actual image. Otherwise I am going to show an default image.

Regards.

Edit

I have created a function:

public string GetImageSourceOrDefault(string orgUrl)
        {
            var req = (HttpWebRequest)WebRequest.Create(orgUrl);
            req.Method = "HEAD";
            try
            {
                using (var resp = req.GetResponse())
                {
                    bool res = resp.ContentType.ToLower(CultureInfo.InvariantCulture)
                        .StartsWith("image/");
                    if (res)
                        return orgUrl;
                    else
                        return "defualt_logo.jpg";
                }
            }
            catch
            {
                return "default_logo.jpg";
            }

        }

This function does the trick. However, for every image it does a request. I have a listview which shows like 220 entries. Using this method messed up the time that listview gets loaded.

Note: this function is natively called using dependency injection.

Maybe further improvements will do. Any ideas?

like image 839
Ege Aydın Avatar asked Jan 07 '23 16:01

Ege Aydın


1 Answers

FFImageLoading CachedImage supports Loading and Error Placeholders (and much more). It's basically a API compatible replacement for Image with additional properties. You could try that.

    var cachedImage = new CachedImage() {
        LoadingPlaceholder = "Loading.png",
        ErrorPlaceholder = "Error.png"
    };

https://github.com/molinch/FFImageLoading

like image 187
Daniel Luberda Avatar answered Jan 15 '23 10:01

Daniel Luberda