Load image from url to ImageView - C#

2020-08-11 16:53发布

问题:

I want to load an image from url to imageview in c# ( android programming ) after search in google i cant find any good result , thank you for helping

i am using xamarin studio

回答1:

The very first hit I got from Google was a thread on the Xamarin forums discussing this exact issue:

private Bitmap GetImageBitmapFromUrl(string url)
{
     Bitmap imageBitmap = null;

     using (var webClient = new WebClient())
     {
          var imageBytes = webClient.DownloadData(url);
          if (imageBytes != null && imageBytes.Length > 0)
          {
               imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
          }
     }

     return imageBitmap;
}

var imageBitmap = GetImageBitmapFromUrl("http://xamarin.com/resources/design/home/devices.png");
imagen.SetImageBitmap(imageBitmap);


回答2:

Both approaches work, but is a good practice to do it asynchronously. Here you have some good examples:

  1. Asynchronous Image Loading in Xamarin Android http://javatechig.com/xamarin/asynchronous-image-loading-xamarin-android
  2. xamarin-store-app image helper https://github.com/xamarin/xamarin-store-app/blob/master/XamarinStore.Droid/Helpers/Images.cs


回答3:

Am using the below class in Xamarin Android:

public class DownloadImageTask : AsyncTask
{
    private ImageView bmImage;
    private ProgressBar progressBar;

    public DownloadImageTask( ImageView bmImage , ProgressBar progressBar)
    {
        this.bmImage = bmImage;
        this.progressBar = progressBar;
    }

    protected override void OnPostExecute( Object result )
    {
        base.OnPostExecute(result);
        bmImage.SetImageBitmap(( Bitmap ) result);
        if (progressBar != null)
            progressBar.Visibility = ViewStates.Gone;
    }


    protected override Object DoInBackground( params Object[] @params )
    {
        var urldisplay = @params[0].ToString();
        Bitmap mIcon11 = null;
        try
        {
            var req = WebRequest.Create(urldisplay);
            var response = req.GetResponse();
            var stream = response.GetResponseStream();

            mIcon11 = BitmapFactory.DecodeStream(stream);
        }
        catch ( Exception e )
        {

        }
        return mIcon11;
    }
}

Execution :

new DownloadImageTask(imgProfile , progressBar).Execute(uri);