Xamarin图像渲染器from byte[]



我正在构建一个应用程序,其中我使用singalR实现流。我使用这个代码示例从一个联系人https://github.com/Guille1878/VideoChat的相机中获取图像(感谢他提供了这样的代码)。

我通过向hub发送json更新了协议:

string arrayJson = JsonConvert.SerializeObject(array);

当图像到达客户端接收器时,我将使用以下代码将其作为byte[]返回:

hubConnection.On<string>("DownloadStream", (streamJson) =>
{
byte[] stream = JsonConvert.DeserializeObject<byte[]>(streamJson);
MyClass.StreamVideoArray.Enqueue(stream);
});

为了使用图像,我创建了一个依赖接口启动,现在使用一个按钮:

private async void StartStopStream_Clicked(object sender, EventArgs e)
{
if (onStreaming)
{
onStreaming = false;
OnStreamStatus.Text = "Stream terminated";
}
else
{
onStreaming = true;
OnStreamStatus.Text = "On stream";
}
int count = 0;
while (onStreaming)
{
await DependencyService.Get<IStreamImgConvert>().BuildImageFrames(count++);
Stream1 = App.StreamImage;
}
}

在注入中,我使用了以下代码:

public async Task BuildImageFrames(int count)
{
await Task.Delay(5);
MyClass.StreamVideoArray.TryDequeue(out byte[] buffer);
if (!(buffer?.Any() ?? false))
return;
try
{
var imageMemoryStream = new MemoryStream(buffer);
\Create a new filepath using the int count
string filePath = Path.Combine(FileSystem.AppDataDirectory, $"File{count}.bmp");
\Create the image to ensure the byte arrays from the buffer is usable
File.WriteAllBytes(filePath, buffer); 
ImageSource imgFromStream = ImageSource.FromStream(() => imageMemoryStream);
\Update the static image which should be update in the xaml page
MyClass.StreamImage.Source = imgFromStream; 
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}

int countinside BuildImageFrames()用于创建图像。这些图像制作得很完美。遗憾的是,byte[]不用于创建静态图像,不显示xaml页面内的任何图像。

我想知道是否有可能创造这样的东西。有人能帮我弄明白吗?

可以提供另一种使用Queue<byte[]>显示流。

感谢@jason提供的链接。通过查看它,它提醒我要在xaml中操作对象,它应该在xaml中完成,MVVM的xaml.cs绑定到页面。

我更正了我的代码,并能够显示图像。在依赖注入中,我使用了以下代码:


public async Task BuildImageFrames(int count)
{
await Task.Delay(5);
MyClass.App.StreamVideoArray.TryDequeue(out byte[] buffer);
if (!(buffer?.Any() ?? false))
return;
try
{
MyClass.App.VideoArray = buffer;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
在xaml页面中,我使用了以下代码:
int count = 0;
while (onStreaming)
{
await DependencyService.Get<IStreamImgConvert>().BuildImageFrames(count++);
if (App.VideoArray != null)
{
ImageSource imgFromStream = ImageSource.FromStream(() => new MemoryStream(App.VideoArray));
Stream1.Source = imgFromStream;
}
}

最新更新