出于某种原因,我无法让下面的代码工作。我正在尝试通过 HTTP 将图像流式传输到浏览器。
[Route("api/v1/camera/live/stream")]
[HttpGet]
public HttpResponseMessage GetStream()
{
logger.Trace($"GET api/v1/camera/live/stream called");
var response = Request.CreateResponse();
response.Content = new PushStreamContent(new Action<Stream, HttpContent, TransportContext>(
async (stream, content, tansportContext) =>
{
try
{
StreamWriter writer = new StreamWriter(stream);
while (HttpContext.Current.Response.IsClientConnected)
{
var image = databuffer.Get<CameraFrame>().LastOrDefault();
if (image != null)
{
MemoryStream ms = new MemoryStream();
ms.SetLength(0);
ms.WriteTo(BytesOf(databuffer.Get<CameraFrame>().Last().Image));
writer.WriteLine("--boundary");
writer.WriteLine("Content-Type: image/jpeg");
writer.WriteLine($"Content-length: {ms.Length}");
writer.WriteLine();
writer.Write(ms.GetBuffer());
writer.Flush();
}
await Task.Delay(33);
}
}
catch (Exception ex)
{
logger.Error($"Streaming error", ex);
throw;
}
logger.Trace("streaming ended");
}));
response.Content.Headers.ContentType =
MediaTypeHeaderValue.Parse("multipart/x-mixed-replace; boundary=--boundary");
return response;
}
private MemoryStream BytesOf(Bitmap image)
{
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms;
}
databuffer.Get() 不断被带有位图帧的相机填充。
当我运行上面的代码时,所有编译都很好。但是当我使用 chrome 导航到 URL 时,它不会显示图像。