【发布时间】:2014-06-05 06:44:31
【问题描述】:
我这里有一个代码,用于从图片 url 下载图片,然后将其保存在图片库中。然后有一个按钮,单击该按钮时,将显示下载的图像。我的问题是,我无法显示下载的图像。这是我下载图片的代码:
public async Task Dwnld(Uri uri)
{
try
{
//filename using global uid to have different names.
var fileName = Guid.NewGuid().ToString() + ".jpg";
// download pic
var httpClient = new HttpClient();
var httpResponse = await httpClient.GetAsync(uri);
byte[] b = await httpResponse.Content.ReadAsByteArrayAsync();
//check if download is success
if (httpResponse.IsSuccessStatusCode)
{
Block.Text = "Download Success";
Block.Foreground = new SolidColorBrush(Colors.Green);
Ring.IsActive = false;
}
else
{
Block.Text = "Error Downloading the Image";
Block.Foreground = new SolidColorBrush(Colors.Red);
await Task.Delay(5000);
Ring.IsActive = false;
}
using (var stream = new InMemoryRandomAccessStream())
{
using (var dw = new DataWriter(stream))
{
// write the raw bytes and store
dw.WriteBytes(b);
await dw.StoreAsync();
// 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));
}
}
}
}
catch (Exception)
{
throw;
}
}
那么这是显示下载图像的任务的代码:
public async Task Pic()
{
var img = await KnownFolders.PicturesLibrary.GetFileAsync(fileName);
var img2 = new BitmapImage();
using (var pictureStream = await img.OpenAsync(FileAccessMode.Read))
{
img2.SetSource(pictureStream);
}
Image.Source = img2;
}
如您所见,Pic() 中有一个未声明的 fileName。我现在的问题是如何使fileName 可用于Pic(),即使它是在Dwnld 中声明的?提前致谢!
【问题讨论】: