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

后端 未结 1 584
温柔的废话
温柔的废话 2021-01-07 04:44

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 Librar

1条回答
  •  走了就别回头了
    2021-01-07 05:11

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

    0 讨论(0)
提交回复
热议问题