WP8:下载并保存GIF到独立存储
本文关键字:独立 存储 GIF 保存 下载 WP8 | 更新日期: 2023-09-27 18:12:46
我想从URL下载一个GIF并保存到WP8的隔离存储。我一直在尝试使用imagetools库解码GIF,然后转换为jpeg,因为silverlight不支持GIF,我想在以后使用web浏览器控件显示保存的图像。我的代码:
ExtendedImage image = new ExtendedImage();
image.LoadingFailed += image_LoadingFailed;
image.LoadingCompleted += (sender, e) =>
{
var isoStore = IsolatedStorageFile.GetUserStoreForApplication();
if (filename.EndsWith(".gif", StringComparison.OrdinalIgnoreCase))
{
GifDecoder gifdecoder = new GifDecoder();
JpegEncoder jpegencoder = new JpegEncoder();
using (var stream = new IsolatedStorageFileStream("somefolder/" + filename, FileMode.Create, isoStore))
{
gifdecoder.Decode(image, stream);
BitmapImage bitmap = new BitmapImage();
using (MemoryStream stream2 = new MemoryStream())
{
jpegencoder.Encode(image, stream2);
bitmap.SetSource(stream2);
}
}
}
image.UriSource = new Uri(imageurl, UriKind.Absolute);
如果您将gif转换为jpeg,您将失去动画。如果你打算使用一个web浏览器控件来显示图像,你根本不需要ImageTools。你能做的是,从远程位置下载gif,将其保存到独立的存储,然后通过将图像路径注入HTML在web浏览器控制器上显示它。
那么,这里是下载图像并将其保存到独立存储的示例代码。
private string savedImagePath = string.Empty;
private void SomeButton_Click(object sender, RoutedEventArgs e)
{
WebClient client = new WebClient();
client.OpenReadCompleted += async (s, args) =>
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (
IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream("savedGifName.gif",
FileMode.Create, storage))
{
await args.Result.CopyToAsync(fileStream);
savedImagePath = fileStream.Name;
}
}
};
client.OpenReadAsync(new Uri("http://www.example.com/someGIF.gif", UriKind.Absolute));
}
现在,您在savedImagePath中获得了独立存储中图像的路径。为了在web浏览器控件上显示该图像,您可以执行以下操作:
private void ViewImageInWebBrowserControl(string ImageURL)
{
string backgroundColor = "<body bgcolor='"#000000'">"; // enter different hex value for different background color
string imageHTML = "<html><head><meta name='"viewport'" " +
"content='"width=440'" id='"viewport'" />" +
"</head>" + backgroundColor + "<IMG SRC='"" +
ImageURL + "'"height='"300'" width='"300'"></body></html>";
browserControl.NavigateToString(imageHTML); // browserControl is created in XAML which is not shown here
}
然后调用ViewImageInWebBrowserControl(savedImagePath);在web浏览器控件中构建HTML并显示GIF(现在位于隔离存储中)。
希望这对你有帮助。