Arthur Rump
Arthur Rump

Reputation: 677

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

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.

Upvotes: 3

Views: 2078

Answers (4)

Astemir Almov
Astemir Almov

Reputation: 446

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);

Upvotes: 0

Rami Kuret
Rami Kuret

Reputation: 3729

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.

Upvotes: 3

Arthur Rump
Arthur Rump

Reputation: 677

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();
}

Upvotes: 1

sebagomez
sebagomez

Reputation: 9619

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.

Upvotes: 0

Related Questions