将图像源设置为 URI [英] Set image source to a URI
问题描述
如果我有一个指向在线图像的链接并且我想将图像源设置为这个 uri,我应该怎么做最好?我正在尝试的代码如下所示.<Image Name="Poster" Height="400" Width="250" VerticalAlignment="Top" Margin="0,10,8,0"/>
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
推荐答案
这是正确的做法.如果您想缓存图像以供以后重用,您可以随时将其下载到独立存储中.使用带有 OpenReadAsync
的 WebClient
- 传递图像 URI 并将其存储在本地.
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);
}
}
}
阅读它会反过来:
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("image.jpg", System.IO.FileMode.Open, file))
{
BitmapImage image = new BitmapImage();
image.SetSource(stream);
image1.Source = image;
}
这篇关于将图像源设置为 URI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!