Azhar Ali Azhar Ali - 5 months ago 50
Android Question

Xamarin forms: how to receive images without storing anywhere locally?

I am working on an app where I want users to get images from web service but don't want them to be stored locally in localdb or local files.
Is there a way to do it?

I am using Xamarin forms.But if it can be done natively it can also be done through xamarin forms.


You can always download the image as a file using a webclient and then an StreamImageSource.

First, you need an interface for a dependency service (I prefer to use WebClient than any third party library so I use these services, feel free to use anything else if you like it, just skip the service part) created on the Forms project:

public interface IDownloader
    byte[] Download(string Url);

Then, you need a dependency service on the Android project:

[assembly: Dependency ( typeof (--yournamespace--.Downloader))]
public class Downloader : IDownloader
    public byte[] Download(string Url)
        //This code is synchronous, I would recommend to do it asynchronously

        WebClient wc = new WebClient();
        return wc.DownloadData(Url);

And then you can download the image and set it as source:

//I assume there exist an image control called img.

var dl = DependencyService.Get<IDownloader> ();
byte[] data = dl.Download(--url to the image--);
var ms = new MemoryStream(data);
img.Source = new StreamImageSource{ Source = (t) => ms };