Shrayansh Sharma
Shrayansh Sharma

Reputation: 217

Download and Save image in Pictures Library through Windows 8 Metro XAML App

I am trying to develop a simple Windows 8 Metro app which simply downloads an image file from a given URL (say http://sample.com/foo.jpg) and then save it to Pictures Library.

I have an image control in the UI to display the downloaded image. I'm also facing difficulty in setting the image source for the image control to the newly downloaded image (actually I'm not even able to download it).

Also, is it possible to store the image file in a particular folder in the Pictures library (if it doesn't exist, then the app should create it)?

I'm really stuck here.

Please help me.

Upvotes: 2

Views: 4057

Answers (1)

Jim O'Neil
Jim O'Neil

Reputation: 23764

Here's some rough code that I believe accomplishes what you want. It assumes you have two image controls (Image1 and Image2) and that you have the Pictures Library capability checked in the manifest. Take a look at the XAML images sample as well

        Uri uri = new Uri("http://www.picsimages.net/photo/lebron-james/lebron-james_1312647633.jpg");
        var fileName = Guid.NewGuid().ToString() + ".jpg";

        // download pic
        var bitmapImage = new BitmapImage();
        var httpClient = new HttpClient();
        var httpResponse = await httpClient.GetAsync(uri);
        byte[] b = await httpResponse.Content.ReadAsByteArrayAsync();

        // create a new in memory stream and datawriter
        using (var stream = new InMemoryRandomAccessStream())
        {
            using (DataWriter dw = new DataWriter(stream))
            {
                // write the raw bytes and store
                dw.WriteBytes(b);
                await dw.StoreAsync();

                // set the image source
                stream.Seek(0);
                bitmapImage.SetSource(stream);

                // set image in first control
                Image1.Source = bitmapImage;

                // write to pictures library
                var storageFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
                    fileName, 
                    CreationCollisionOption.ReplaceExisting);

                using (var storageStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await RandomAccessStream.CopyAndCloseAsync(stream.GetInputStreamAt(0), storageStream.GetOutputStreamAt(0));
                }
            }
        }

        // read from pictures library
        var pictureFile = await KnownFolders.PicturesLibrary.GetFileAsync(fileName);
        using ( var pictureStream = await pictureFile.OpenAsync(FileAccessMode.Read) )
        {
            bitmapImage.SetSource(pictureStream);
        }
        Image2.Source = bitmapImage;
    }

Upvotes: 9

Related Questions