如果我有一个在线图像的链接,并且我想将图像源设置为这个 uri,我应该怎么做最好?我正在尝试的代码如下所示。
<Image Name="Poster" Height="400" Width="250" VerticalAlignment="Top" Margin="0,10,8,0"/>
BitmapImage imgSource = new BitmapImage();<br/>
imgSource.UriSource = new Uri(movie.B_Poster, UriKind.Relative);<br/>
Poster.Source = imgSource;
此外,如果我想缓存此图像以再次加载它,该怎么做?
谢谢
最佳答案
这是正确的做法。如果您想缓存图像供以后重复使用,您可以随时将其下载到独立存储中。将 WebClient
与 OpenReadAsync
结合使用 - 传递图像 URI 并将其存储在本地。
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);
}
}
}
阅读它会反过来:
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("image.jpg", System.IO.FileMode.Open, file))
{
BitmapImage image = new BitmapImage();
image.SetSource(stream);
image1.Source = image;
}
关于c# - 将图像源设置为 URI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6940880/