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

牧云@^-^@ 提交于 2019-12-12 07:24:50

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/16858376/download-and-save-image-in-pictures-library-through-windows-8-metro-xaml-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!