我从服务器(asp网络核心)将图像作为流内容从服务器获取到我的xamarin客户端应用程序,这是服务器上控制器中的httpget请求:
[HttpGet("getimg")]
public async Task<IActionResult>Getimg(string imgpath)
{
var image = System.IO.File.OpenRead(imgpath);
return File(image, "image/jpeg");
}
在我的xamarin客户端应用中,我正在使用它从服务器下载照片:
public async Task<System.IO.Stream>DownloadPhoto(string imagepath)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer", Settings.AccessToken);
var stream = await client.GetStreamAsync(Constants.BaseApiAddress + "exercise/getimg?imgpath=" + imagepath);
return stream;
}
然后我填充List System.IO.Stream并从中获取ImageSources列表。 在XAML中,图像与FF加载图像绑定在列表视图中:
<ffimageloading:CachedImage HorizontalOptions="Start"
VerticalOptions="Center" WidthRequest="100" HeightRequest="100"
Grid.Column="0" Grid.RowSpan="2" Source = "{Binding _firstImagePathSource}">
</ffimageloading:CachedImage>
这是列表视图的一部分,因为我还有其他文本内容要显示。 第一次加载时一切正常,但是当我向下滚动然后返回时,当listview重新加载图像时,重新加载的图像放置在错误的位置(例如:第一个和第二个单元格中的图像更改了它们的位置)。发生了什么?缓存出了点问题?
如果有更好的方法可以从服务器上下载照片(但需要获得许可),请告诉我。
更新!!!
我认为我已经解决了这个问题: 受返回流的影响,我正在使用它下载照片:
public async Task<byte[]> DownloadPhotos(string imagepath)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new
AuthenticationHeaderValue(
"Bearer", Settings.AccessToken);
var result= await
client.GetByteArrayAsync(Constants.BaseApiAddress
+ "exercise/getimgs?imgpath=" + imagepath);
return result;
}
只需使用以下命令从字节数组中获取图像源:
public ImageSource BytesToImageSource(byte[] bytes)
{
return ImageSource.FromStream(() => new MemoryStream(bytes));
}
现在,将图像重新加载到正确的位置。