【问题标题】:Download and Save image in Pictures Library through Windows 8 Metro XAML App通过 Windows 8 Metro XAML 应用程序在图片库中下载和保存图像
【发布时间】:2013-05-31 13:24:32
【问题描述】:

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

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

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

我真的被困在这里了。

请帮帮我。

【问题讨论】:

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


    【解决方案1】:

    这里有一些粗略的代码,我相信它们可以实现您想要的。它假定您有两个图像控件(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;
        }
    

    【讨论】:

    • 非常感谢!这正是我一直在寻找的。 :-)
    • 如何在 Win 8 Javascript 应用上实现同样的操作?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2012-08-26
    • 2023-03-15
    相关资源
    最近更新 更多