简体   繁体   中英

Set image source to a URI

If i have a link to an image online and i want to set the image source to this uri, how should i do it best? The code i'm trying is shown below.
<Image Name="Poster" Height="400" Width="250" VerticalAlignment="Top" Margin="0,10,8,0"/>

BitmapImage imgSource = new BitmapImage();
imgSource.UriSource = new Uri(movie.B_Poster, UriKind.Relative);
Poster.Source = imgSource;

Also, if i want to cache this image to load it again how is this done?
Thanks

This is the right way to do it. If you want to cache the image for later re-use, you could always download it in the Isolated Storage. Use a WebClient with OpenReadAsync - pass the image URI and store it locally.

WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri("IMAGE_URL"));

void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();

    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("image.jpg", System.IO.FileMode.Create, file))
    {
        byte[] buffer = new byte[1024];
        while (e.Result.Read(buffer, 0, buffer.Length) > 0)
        {
            stream.Write(buffer, 0, buffer.Length);
        }
    }
}

Reading it will be the other way around:

using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("image.jpg", System.IO.FileMode.Open, file))
{
    BitmapImage image = new BitmapImage();
    image.SetSource(stream);

    image1.Source = image;
}

You've done it correctly.

To cache an image, you would download it to your local file store with either a WebClient (easiest) or using the WebRequest - WebResponse mechanism. Then, next time you go to set the image location, check if it exists locally. If so, set it to the local file. If not, set it to the remote file and download.

PS. You'd need to keep track of these and delete old files, or you'll fill up the phone's memory very quickly.

The way you are setting the image source in code-behind is absolutely fine. The other alternative, if you are using binding / MVVM is to convert your string URL to an image source using a converter:

public class StringToImageConverter : IValueConverter
{

  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    string url = value as string;
    Uri uri = new Uri(url);
    return new BitmapImage(uri);
  }

  public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    throw new NotImplementedException();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM