我这里有一个代码用于从图片网址下载图片然后将其保存在图片库中。然后有一个按钮,当点击时,将显示下载的图像。我的问题是,我无法显示下载的图像。这是我下载图片的代码:
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;
}
如您所见,fileName
中有Pic()
未声明。我现在的问题是如何使fileName
可用于Pic()
,即使它已在Dwnld
中声明了?提前谢谢!
答案 0 :(得分:1)
您需要更改两种方法的签名。
public async Task<string> Dwnld(Uri uri)
{
...
await RandomAccessStream.CopyAndCloseAsync(stream.GetInputStreamAt(0), storageStream.GetOutputStreamAt(0));
return fileName;
并且
public async Task Pic(string fileName)
答案 1 :(得分:0)
我最终从谷歌搜索了几个页面并尝试了不同的键盘然后我想出了答案。
我宣布private string fileName;
然后删除var
中的dwnld()
。比你回答