Saving an image from the web to the Saved Pictures folder in Windows Phone 8.1 RT C#

自古美人都是妖i 提交于 2019-12-12 12:27:20

问题


How can I save an image to the Saved Pictures folder in Windows Phone 8.1 RT? I downloaded the image from the web using HttpClient.


回答1:


You just need this

var url = "Some URL";
var fileName = Path.GetFileName(url.LocalPath);
var thumbnail = RandomAccessStreamReference.CreateFromUri(url);

var remoteFile = await StorageFile.CreateStreamedFileFromUriAsync(fileName, url, thumbnail);
await remoteFile.CopyAsync(KnownFolders.SavedPictures, fileName, NameCollisionOption.GenerateUniqueName);

You need to set the Pictures Library capability in your manifest.




回答2:


I solved it thanks to mSpot Inc on the MSDN-forums. The code I use now:

StorageFolder picsFolder = KnownFolders.SavedPictures;
StorageFile file = await picsFolder.CreateFileAsync("myImage.jpg", CreationCollisionOption.GenerateUniqueName);

string url = "http://somewebsite.com/someimage.jpg";
HttpClient client = new HttpClient();

byte[] responseBytes = await client.GetByteArrayAsync(url);

var stream = await file.OpenAsync(FileAccessMode.ReadWrite);

using (var outputStream = stream.GetOutputStreamAt(0))
{
    DataWriter writer = new DataWriter(outputStream);
    writer.WriteBytes(responseBytes);
    writer.StoreAsync();
    outputStream.FlushAsync();
}



回答3:


If you want the user to pick for the file location you need to use the FileSavePicker with pictureLibrary as the SuggestedStartLocation.

If you want to save it without the user to select the destination you need to use something like this:

Windows.Storage.KnownFolders.picturesLibrary.createFileAsync

I believe in both cases you need to set the Pictures Library capability in your manifest.




回答4:


At the moment, I use this native implementation:

var url = new Uri(UriString, UriKind.Absolute);
var fileName = Path.GetFileName(url.LocalPath);

var w = WebRequest.CreateHttp(url);
var response = await Task.Factory.FromAsync<WebResponse>(w.BeginGetResponse, w.EndGetResponse, null);
await response.GetResponseStream().CopyToAsync(new FileStream(ApplicationData.Current.LocalFolder.Path + @"\" + fileName, FileMode.CreateNew));
var file = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
await file.CopyAsync(KnownFolders.SavedPictures, fileName, NameCollisionOption.FailIfExists);


来源:https://stackoverflow.com/questions/27081229/saving-an-image-from-the-web-to-the-saved-pictures-folder-in-windows-phone-8-1-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!