我使用下面的代码在Windows Phone 8中保存远程图像。但是我在SaveJpeg()方法调用中一直遇到System.NotSupportedException: Specified method is not supported.
异常。
我尝试了不同的方法调用组合(你可以看到注释行)。我无法弄清楚我做错了什么。
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(imageUrl);
await Task.Run(async () =>
{
if (response.IsSuccessStatusCode)
{
// save image locally
Debug.WriteLine("Downloading image..." + imageName);
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!myIsolatedStorage.DirectoryExists("Images"))
myIsolatedStorage.CreateDirectory("Images");
string path = imageName;
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(path);
var buffer = await response.Content.ReadAsStreamAsync();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
BitmapImage bitmap = new BitmapImage { CreateOptions = BitmapCreateOptions.None };
bitmap.SetSource(buffer);
WriteableBitmap wb = new WriteableBitmap(bitmap);
//System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 98);
});
fileStream.Close();
}
}
});
}
答案 0 :(得分:2)
通过将代码块放在BeginInvoke块中,您将调用另一个线程(“UI线程”)上的SaveJpeg到调用fileStream.Close()
的代码。
实际上,这意味着很有可能在fileStream.Close()
之前调用wb.SaveJpeg
。
如果您在BeginInvoke块内移动fileStream.Close()
,wb.SaveJpeg()
之后它应该可以正常工作。