0

所以我的目标是制作一个基本的基本视频流应用程序。

为此,我不断通过网络摄像头捕捉图像并通过NetworkStream课堂发送它们(我知道这是一个粗略的解决方案,但正如我所说,它只是一个基本的基本应用程序,不适用于生产环境)。

所以现在问题出在这一行

Image img = Image.FromStream(receiveStream);

现在这会阻塞线程,它不会从这条线继续前进。假设从流中捕获图像所以这里有什么问题?

4

2 回答 2

3

You haven't gotten around to the real problem yet. The Image.FromStream() method requires a stream whose CanSeek property is true. The image decoder requires it. This is however not the case for a NetworkStream, it cannot support seeking.

You must store the image in a MemoryStream first. Once that's filled, set the Position back to 0 and call Image.FromStream(). Make sure you don't dispose or re-use the MemoryStream, that causes a very hard to diagnose GenericException later. The image decoder is lazy and need to be able to access the stream when the image is rendered.

To make this work, you must know how much data to read from the NetworkStream. In other words, you need to know how many bytes are present in a frame. You can do so by having the transmitter first write an int, then the bytes in the image. On the reading end you can then first read the 4 bytes from the stream and use BitConverter.ToInt32() to recover the length. And can simply count-off the bytes in the stream to know when the MemoryStream is ready and Image.FromStream() can be called.

Once you've got that into place, you'll either have solved whatever bug is ailing your current code or have a very good way to debug it.

于 2013-08-03T13:56:58.923 回答
3

我怀疑问题是NetworkStream没有关闭,所以Image.FromStream不知道当前图片何时完成。

假设您负责协议,您可以为每个图像添加长度前缀,然后当您从流中读取时,您可以将确切的字节数读入字节数组,用 a 包装,MemoryStream然后传递到Image.FromStream. 这样,每次调用Image.FromStream都会获得一个流,该流在单个图像之后结束。

所以你NetworkStream看起来像这样:

Length (4 bytes)
Data for one image
Length (4 bytes)
Data for one image
// etc
于 2013-08-03T07:57:42.063 回答