Set image source to a URI

前端 未结 3 1379
臣服心动
臣服心动 2021-01-23 12:08

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.

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-23 12:33

    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;
    }
    

提交回复
热议问题