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.

Refresh Image Source with timer

EsegeEsege Member ✭✭

In my ContentPage i have only an image. I need to refresh this image's source from an uri every five seconds. So I just wrote this.

            Device.StartTimer(new TimeSpan(0, 0, 5), () =>
            {

                Device.BeginInvokeOnMainThread(() =>
                {
                    camPhoto.Source = ImageSource.FromUri(new Uri(urilink));
                });
                return true; 
            });

Timer does work, every five seconds. (My link doesn't change but the resulting image of the link does change every 5 seconds.) But the image doesn't change after the first image fetching. Android, UWP behaves the same way. How can I fix this?

Best Answer

  • EsegeEsege Member ✭✭
    Accepted Answer

    Instead of ImageSource.FromUri I used ImageSource.FromStream and it worked fine.

    camPhoto.Source = ImageSource.FromStream(() => GetStreamFromUrl(_link));
            private Stream GetStreamFromUrl(string url)
            {
                byte[] imageData = null;
    
                using (var wc = new System.Net.WebClient())
                    imageData = wc.DownloadData(url);
    
                return new MemoryStream(imageData);
            }
    

Answers

  • EsegeEsege Member ✭✭
    Accepted Answer

    Instead of ImageSource.FromUri I used ImageSource.FromStream and it worked fine.

    camPhoto.Source = ImageSource.FromStream(() => GetStreamFromUrl(_link));
            private Stream GetStreamFromUrl(string url)
            {
                byte[] imageData = null;
    
                using (var wc = new System.Net.WebClient())
                    imageData = wc.DownloadData(url);
    
                return new MemoryStream(imageData);
            }
    
Sign In or Register to comment.