通过Windows 8 Metro XAML App在图片库中下载并保存图像

时间:2013-05-31 13:24:32

标签: c# .net windows-8 microsoft-metro download

我正在尝试开发一个简单的Windows 8 Metro应用程序,只需从给定的URL(例如http://sample.com/foo.jpg)下载图像文件,然后将其保存到图片库。

我在UI中有一个图像控件来显示下载的图像。 我也很难将图像控件的图像源设置为新下载的图像(实际上我甚至无法下载它)。

此外,是否可以将图像文件存储在图片库中的特定文件夹中(如果它不存在,那么应用应该创建它)?

我真的被困在这里。

请帮帮我。

1 个答案:

答案 0 :(得分:9)

以下是一些我认为可以实现您想要的粗略代码。它假设您有两个图像控件(Image1和Image2),并且您在清单中检查了图片库功能。看看XAML images sample以及

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