Image placeHolder

Eduardo Gomez Romero 1,355 Reputation points
2024-12-08T20:43:55.5566667+00:00

For some reason

the URL image

https://www.sciencedaily.com/images/scidaily-icon.png

doesn't want to show on desktop in my collection view, even though is there

Android

User's image

Desktop
User's image

Website (Edge)User's image

So, I have two possible solutions

  1. find out why it doesn't want to load
  2. Showing a placeholder (The problem with this approach, is that I cannot use this
              <CollectionView.ItemTemplate>
                  <DataTemplate x:DataType="models:Article">
                      <Border>
                          <Grid
                              Padding="10"
                              RowDefinitions="250,Auto,Auto,Auto">
                              <Image
                                  Aspect="AspectFill"
                                  HeightRequest="250"
                                  Source="{x:Binding UrlToImage,
                                                     FallbackValue=no_image.png,
                                                     TargetNullValue=no_image.png}"
                                  VerticalOptions="Center" />
    
    Since technically the image I not null) User's image this is my httpService
    public class HttpService: IHttpService
    {
        readonly HttpClient _httpClient;
        readonly ILogger<HttpService> _logger;


        public HttpService(HttpClient httpClient, ILogger<HttpService> logger)
        {
            _httpClient = httpClient;
            _logger = logger;

            // Set User-Agent header once in the constructor
            _httpClient.DefaultRequestHeaders.Add(
                "User-Agent",
                "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Googlebot/2.1; +http://www.google.com/bot.html)");

        }

        public async Task<T?> GetAsync<T>(string url)
        {
            try
            {
                var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();

                var data = await response.Content.ReadFromJsonAsync<T>();
                return data;
            }
            catch (HttpRequestException ex)
            {
                _logger.LogError("HttpRequestException in HttpService: {Message}", ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Unexpected error in HttpService");
            }

            return default;
        }
    }

Developer technologies | .NET | .NET MAUI
0 comments No comments
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 50,126 Reputation points Microsoft External Staff
    2024-12-09T07:21:07.3266667+00:00

    Hello,

    There are two reasons why this image cannot be loaded on the Windows platform.

    1. The image link you provided needs to be authenticated on Windows. This is not from a public image hosting service. This link cannot be directly parsed as an image on Windows. As a public image resource, its access should be unlimited. For example, you can replace the image link with the image resource you published in Q&A.

    https://learn-attachment.microsoft.com/api/attachments/5667ecd8-9690-4b02-a000-901860c79390?platform=QnA

    1. Your Image control uses the Aspect="AspectFill" attribute and does not assign a width to the Image. In this case, the image will be stretched to the full width of the screen. You can use Aspect="AspectFit" to make the image's width automatically adjust.

    In summary, you need to push the Icon image to a public image hosting service with unlimited access and set the correct attributes or width and height for the Image.

    Update:

    Since the success of obtaining the image link needs to be judged through Http request, you need to use ValueConverter to implement this function. Please refer to the following code example:

    internal class ImgSourceConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var source = value as string;
            if (source != null) {
                var res = GetHttpImage(source); // The icon displayed on the page is determined by judging whether the HTTP request is successful.
                if (res) {
                    return value;
                }                   
            }
            return "dotnet_bot.png";
        }
     
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return true;
        }
        private bool GetHttpImage(string url)
        {
            var client = new HttpClient();
            try
            {
                var response = client.GetAsync(url).Result;
                if (response != null && response.IsSuccessStatusCode)
                {
                    return true;
                }
            }
            catch (Exception ex) {
                return false;
            }
            return false;
     
        }
    }
    
    <Image 
      Aspect="AspectFill"
      HeightRequest="250"
        WidthRequest="250"
      Source="{x:Binding UrlToImage,
                         Converter={StaticResource ImgSourceConverter}}"
      VerticalOptions="Center" />
    

    You could refer to Binding value converters for more details.

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.