如何共享已消耗的内存流?

时间:2016-02-24 20:03:36

标签: c# xamarin.forms

我需要在Xamarin.Forms应用的不同页面上共享图像。

在页面上加载图像后,我无法重复使用ImageSource和流。因此,我还需要在其他页面上加载相同的图像。

我发布了相关问题here

以下是一些代码:

public PhotoCapturedViewModel(IScreen screen, Stream stream) : base(screen, "")
{
    Photo = ImageSource.FromStream(() => stream); // This stream was already used on another page
    Apply = new DelegateCommand(_ => Publish(APPLY_PHOTO, new RenderedPhoto(stream, Description)));
}

2 个答案:

答案 0 :(得分:1)

我通过立即将最近创建的流转换为字节数组解决了我的问题。

然后我通过传递字节数组来生成新的内存流。

<强>创作:

var file = await service.TakePhotoAsync(mediaOptions);
var stream = file.GetStream();

using (var memoryStream = new MemoryStream())
{
    stream.CopyTo(memoryStream);
    var image = memoryStream.ToArray();
    Publish(PHOTO_CAPTURED, new ImageCaptureNavigationArgs(image));
}

<强>导航

static void OnPhotoCaptured(object obj)
{
    var args = obj as ImageCaptureNavigationArgs;
    var screen = IOCServiceRegistration<IUnityContainer>.Container.Resolve(typeof(IScreen)) as IScreen; // ReactiveUI dependency kludge. Sigh...
    screen.Router.Navigate.Execute(new PhotoCapturedViewModel(screen, args.Stream));
}

<强>用法:

public partial class PhotoCapturedViewModel : BaseViewModel
{
    public PhotoCapturedViewModel(IScreen screen, byte[] image) : base(screen, "")
    {
        var memoryStream = new MemoryStream(image);
        Photo = ImageSource.FromStream(() => memoryStream);
        Apply = new DelegateCommand(_ => Publish(APPLY_PHOTO, new RenderedPhoto(image, Description)));
    }

答案 1 :(得分:0)

我解决这个问题的方法不是使用相同的流,而是简单地将新图像源设置为原始图像的源。

尝试这样的事情:

public PhotoCapturedViewModel(IScreen screen, Image originalImage) :     base(screen, "")
{
    Photo = new Image() {Source = originalImage.Source};
}