我正在尝试开发一个简单的Windows8Metro应用程序,它只需从给定的网址(比如http://sample.com/foo.jpg)下载一个图像文件,然后将其保存到图片库。
我在UI中有一个图像控件来显示下载的图像。我还面临着将图像控件的图像源设置为新下载的图像的困难(实际上我甚至无法下载它)。
此外,是否可以将图像文件存储在Pictures库中的特定文件夹中(如果不存在,则应用程序应创建它)?
我真的被困在这里了。
请帮帮我。
发布于 2013-06-01 09:46:30
这里有一些粗略的代码,我相信它们可以实现您想要的功能。它假设您有两个图像控件(Image1和Image2),并且在清单中选中了Pictures Library功能。还可以看看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;
}https://stackoverflow.com/questions/16858376
复制相似问题