(Metro学习三)图片uri保存到本地图片库
生活随笔
收集整理的這篇文章主要介紹了
(Metro学习三)图片uri保存到本地图片库
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
已知網絡上圖片的uri地址,如何將網絡圖片保存到本地呢?代碼如下:
保存圖片到本地 private async Task SaveImageFromUrl(string uri, string filename){var rass = RandomAccessStreamReference.CreateFromUri(new Uri(uri));IRandomAccessStream inputStream = await rass.OpenReadAsync();Stream input = WindowsRuntimeStreamExtensions.AsStreamForRead(inputStream.GetInputStreamAt(0));try{//獲取圖片擴展名的GuidStorageFolder folder = KnownFolders.PicturesLibrary;StorageFile outputFile = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);using (IRandomAccessStream outputStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite)){Stream output = WindowsRuntimeStreamExtensions.AsStreamForWrite(outputStream.GetOutputStreamAt(0));await input.CopyToAsync(output);output.Dispose();input.Dispose();}}catch (Exception){}}根據圖片uri保存到本地的函數,即以上為圖片uri和圖片名稱的轉換,另以下三種轉換:
1、FileName轉換為Stream,圖片可為本地圖片,也可為應用程序中圖片
圖片轉換為流 private async Task<Stream> ImageNameToStream(string filename){try{////本地圖片庫//StorageFolder folder = KnownFolders.PicturesLibrary;//本地圖片庫//StorageFile storagefile = await folder.GetFileAsync(filename);//應用程序Images文件夾圖片Uri _baseUri = new Uri("ms-appx:///");Uri uri = new Uri(_baseUri, "../Images/" + filename);StorageFile storagefile = await StorageFile.GetFileFromApplicationUriAsync(uri);IRandomAccessStream irandom = await storagefile.OpenAsync(FileAccessMode.Read);Stream outPutstream = irandom.GetInputStreamAt(0).AsStreamForRead();return outPutstream;}catch (Exception ex){return null;}}2、Stream轉換成文件,圖片保存到本地
流轉換成本地圖片 private async Task StreamToFileName(Stream inputstream, string filename){try{StorageFolder folder = KnownFolders.PicturesLibrary;StorageFile outputFile = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);using (IRandomAccessStream output = await outputFile.OpenAsync(FileAccessMode.ReadWrite)){Stream outputstream = WindowsRuntimeStreamExtensions.AsStreamForWrite(output.GetOutputStreamAt(0));await inputstream.CopyToAsync(outputstream);outputstream.Dispose();inputstream.Dispose();}}catch (Exception ex){}}3、圖片Uri轉換成流
網絡圖片Uri轉換成流 private async Task<Stream> UriToStream(string uri){var rass = RandomAccessStreamReference.CreateFromUri(new Uri(uri));IRandomAccessStream inputStream = await rass.OpenReadAsync();Stream input = WindowsRuntimeStreamExtensions.AsStreamForRead(inputStream.GetInputStreamAt(0));return input;}若有其他流與Metro流之間的轉換,參考http://www.cnblogs.com/jing870812/archive/2012/04/12/2444870.html
?
?
?
轉載于:https://www.cnblogs.com/wenqin/archive/2012/10/11/2720288.html
總結
以上是生活随笔為你收集整理的(Metro学习三)图片uri保存到本地图片库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: css结构和重叠之选择器的特殊性
- 下一篇: 什么是重构,什么不是重构