(Metro学习三)图片uri保存到本地图片库
已知网络上图片的uri地址,如何将网络图片保存到本地呢?代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 { //获取图片扩展名的Guid StorageFolder 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,图片可为本地图片,也可为应用程序中图片
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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转换成文件,图片保存到本地
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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转换成流
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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