【问题标题】:Xamarin: passing a downloaded image from a Page to another oneXamarin:将下载的图像从页面传递到另一个页面
【发布时间】:2020-10-01 15:16:40
【问题描述】:

虽然我认为这将是一项简单的任务,但我很难将图像通过页面显示到必须全屏显示的新页面。 它是这样工作的:

    Stream imgStream = await _restService.GetArticleImgPath((int) barcode.Oarti);
    byte[] bytes = null;
    articleImg.Source = ImageSource.FromStream(() => imgStream};
       

这样就可以了。在四处搜索时,我找到了使用byte[] 的解决方案,但我没有运气。 这是我正在尝试的:

byte[] bytes = null;
articleImg.Source = ImageSource.FromStream(() => {
    using (var memoryStream = new MemoryStream())
        {
            imgStream.CopyTo(memoryStream);
            imgStream.Dispose();
            bytes = memoryStream.ToArray();
        }
        imgStream.Dispose();
        return imgStream;
        });

我仍然收到System.ObjectDisposedException: 'Cannot access a closed Stream.'。 我怎样才能简单地将相同的图像传递给新页面,仍然使用新页面的构造函数?

【问题讨论】:

  • 我建议写入一个文件,然后将文件路径传递给新页面

标签: image xamarin stream


【解决方案1】:

您可以尝试将Stream 转换为byte[],然后将其传递到下一页。

例如,使用以下方法:

public static class StreamExtensions
{
    public static byte[] ToByteArray(this Stream stream)
    {
        stream.Position = 0;
        byte[] buffer = new byte[stream.Length];
        for (int totalBytesCopied = 0; totalBytesCopied < stream.Length;)
            totalBytesCopied += stream.Read(buffer, totalBytesCopied, Convert.ToInt32(stream.Length) - totalBytesCopied);
        return buffer;
    }
}

然后就可以转换了(不关心Stream会不会被关闭):

//Stream imgStream = await _restService.GetArticleImgPath((int) barcode.Oarti);
// Here we can not dealing with a remote file, we need to store it in local file first 
Stream imgStream = getLocalfile();
byte[] bytes = StreamExtensions.ToByteArray(imgStream);

【讨论】:

  • 它说“流不支持搜索”
  • @exrezzo Okey,这是我的错误。仅本地文件支持查找。您可能需要将文件复制到本地文件系统。正如 Jason 所说,我们需要将 steam 存储到本地文件中,然后我们才能处理它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-16
  • 2016-01-24
相关资源
最近更新 更多