开发应用经常要将网络上的图片存储下来,在8.1有FileSavePicker可以用,但用户反映每次都要选择路径好麻烦,于是开始寻找直接存到照片库的方法,首先肯定要从网络上拿到图片流,然后在图片库里新建一个文件,把图片流弄到文件里去就大功告成了,各种查MSDN后终于解决,话不多说,上代码
string fileName = "picture"+DateTime.Now.Ticks+".jpg"; //在SavePictures文件夹下生成一个空文件用于保存图片 StorageFile destinationFile = await KnownFolders.SavedPictures.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); using(var response =await HttpWebRequest.Create(savePictureInfo.imageUri).GetResponseAsync()) { //获取到图片流 using (Stream responseStream = response.GetResponseStream()) { using (var destinationStream = await destinationFile.OpenAsync(FileAccessMode.ReadWrite)) { using (var destinationOutputStream = destinationStream.GetOutputStreamAt(0)) { await RandomAccessStream.CopyAndCloseAsync(responseStream.AsInputStream(), destinationStream); } } } //获取文件更新状态 FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(destinationFile); if (status == FileUpdateStatus.Complete) { string SAVE_SUCCESS = loader.GetString("uSaveSuccess"); await new MessageDialog(SAVE_SUCCESS).ShowAsync(); } else { string SAVE_FAILED = loader.GetString("uSaveFailed"); await new MessageDialog(SAVE_FAILED).ShowAsync(); }
刚学WP不久,如有错误,欢迎指正。
时间: 2024-10-13 23:49:24