Save Image in Windows Store Application

Overview

Recently I was working on a Windows Store Application in which we are fetching images based on a search using Flicker. You can refer here to see that app.

Now what I want is that when I click on a photo then it is saved on the local folder. So, let's start with the following procedure.

Save Image

In this section, we'll create the asynchronous method to download the image and save it in the local folder. Use the following procedure.

Step 1: When we click on the image in the grid , we need to save the URL of that specific image. Update the code with the following code:

  1. private void grdFlickrImageOutput_ItemClick(object sender, ItemClickEventArgs e)  
  2. {  
  3.     FlickerPhoto selectedPhoto = e.ClickedItem as FlickerPhoto;  
  4.     var url = Convert.ToString(selectedPhoto.ImageUrl);  
  5.     DownloadImage(url);  
  6. }  

 

In the preceding code, we have converted the code to a string and passed that URL as a parameter in a method.

Step 2: Now we will create the download method to save the image in the local folder. Create the method as shown below:

  1. private async void DownloadImage(string url)  
  2. {  
  3.     string FileName = Path.GetFileName(url);  
  4.     httpClient = new HttpClient();  
  5.     HttpResponseMessage message = await httpClient.GetAsync(url);  
  6.    
  7.     StorageFolder myfolder = ApplicationData.Current.LocalFolder;  
  8.     StorageFile SampleFile = await myfolder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting);  
  9.     byte[] file = await message.Content.ReadAsByteArrayAsync();  
  10.     await FileIO.WriteBytesAsync(SampleFile, file);  
  11.     var files = await myfolder.GetFilesAsync();  
  12. }  

 

In the preceding code, we have passed the URL in the HttpClient method. We have defined the folder location as a local folder and to save the file we saved that file in the described folder.

That's it.

Up Next
    Ebook Download
    View all
    Learn
    View all