更新时间:2023-10-10 19:21:22
这是如何做到这一点的工作示例。其逻辑如下:
This is a working example on how to do that. The logic is as follow :
的LoadImage
方法。 的LoadImage
方法从网络下载的图像,并调用事件处理程序时,下载完成。 DownloadCompleted $那么C $ C>方法),保存图片到独立存储和
再次调用的LoadImage。参照点2为下发生什么。
LoadImage
method.LoadImage
method will download the image from web and call an event handler when download completed.DownloadCompleted
method) will then, save the image to Isolated Storage and call LoadImage
again. Refer to point 2 for what happen next.您想在以后改进它来实现MVVM,并使用数据绑定。
You may want to improve it later to implement MVVM and using DataBinding.
参考文献:的 nickharris.net ,的 geekchamp.com
string imageName = "myImage.jpg";
string imageUrl = "http://political-leader.vzons.com/ArvindKejriwal/images/icons/landing.png";
public MainPage()
{
InitializeComponent();
LoadImage();
}
private void LoadImage()
{
BitmapImage bi = new BitmapImage();
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
//load image from Isolated Storage if it already exist
if (myIsolatedStorage.FileExists(imageName))
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(imageName, FileMode.Open, FileAccess.Read))
{
bi.SetSource(fileStream);
imageBrushName.ImageSource = bi;
}
}
//else download image to Isolated Storage
else
{
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(DownloadCompleted);
wc.OpenReadAsync(new Uri(imageUrl, UriKind.Absolute), wc);
}
}
}
private void DownloadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null && !e.Cancelled)
{
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(imageName);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(e.Result);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
}
//after image saved to Iso storage, call LoadImage method again
//so the method will set imageBrush's ImageSource to image in Iso storage
LoadImage();
}
catch (Exception ex)
{
//Exception handle appropriately for your app
}
}
else
{
//Either cancelled or error handle appropriately for your app
}
}