我有一台服务器,它不断传输 jpeg 图像,例如延时视频源。我需要在 C# WinForm TCP 客户端中显示这些图像,并且在流式传输时遇到问题。
我在这里和其他有类似问题的网站上阅读了许多帖子,但没有一个能够为我的问题提供解决方案。
我有以下代码,旨在从服务器检索图像并使用 PictureBox 控件显示它:(图像流中有标题信息)
while (true)
{
NetworkStream stream = m_client.GetStream(); //Get the data stream from the server
//Load Image
while (stream.DataAvailable)
{
byte[] buffer = new byte[m_client.ReceiveBufferSize];
stream.Read(buffer, 0, buffer.Length);
string tempString = System.Text.Encoding.ASCII.GetString(buffer);
//split header info and data into separate strings
string[] splitString = tempString.Split(new string[] { "]" }, 2, StringSplitOptions.None);
splitString[0] = splitString[0].Replace(@"\", "");
//split header info into separate strings for use later
string[] imageInfo = splitString[0].Split('|');
int size = Convert.ToInt32(tempString.Length);
//int offset = splitString[0].Length;
buffer = new byte[size];
stream.Read(buffer, 0, buffer.Length);
//Convert Image Data To Image
MemoryStream imageStream = new MemoryStream(buffer, 0, buffer.Length);
imageStream.Position = 0;
Bitmap img = new Bitmap(imageStream);
//set the image display box properties
VideoBox.Width = img.Width;
VideoBox.Height = img.Height;
VideoBox.Image = img; //Show the image in the picturebox
}
stream.Flush();
}
目前,此代码运行至Bitmap img = new Bitmap(imageStream);
其给出参数无效错误的位置。
这是我第一次这样做,所以对接下来要尝试什么有点迷茫,我花了最后一天尝试不同的解决方案,但这个似乎是迄今为止最好的(我认为:s)。
如果有人能指出我做错了什么或遗漏了什么,我将不胜感激。