我正在尝试通过网络流发送图像,我有一个sendData和Getdata函数,但在使用Image.FromStream函数时总是得到无效的参数
这是我的代码:我从屏幕上获取图片,然后将其转换为byte[],并将其插入到我通过networkStream发送的内存流中。
private void SendData()
{
StreamWriter swWriter = new StreamWriter(this._nsClient);
// BinaryFormatter bfFormater = new BinaryFormatter();
// this method
lock (this._secLocker)
{
while (this._bShareScreen)
{
// Check if you need to send the screen
if (this._bShareScreen)
{
MemoryStream msStream = new MemoryStream();
this._imgScreenSend = new Bitmap(this._imgScreenSend.Width, this._imgScreenSend.Height);
// Send an image code
swWriter.WriteLine(General.IMAGE);
swWriter.Flush();
// Copy image from screen
this._grGraphics.CopyFromScreen(0, 0, 0, 0, this._sizScreenSize);
this._imgScreenSend.Save(msStream, System.Drawing.Imaging.ImageFormat.Jpeg);
msStream.Seek(0, SeekOrigin.Begin);
// Create the pakage
byte[] btPackage = msStream.ToArray();
// Send its langth
swWriter.WriteLine(btPackage.Length.ToString());
swWriter.Flush();
// Send the package
_nsClient.Write(btPackage, 0, btPackage.Length);
_nsClient.Flush();
}
}
}
}
private void ReciveData()
{
StreamReader srReader = new StreamReader(this._nsClient);
string strMsgCode = String.Empty;
bool bContinue = true;
//BinaryFormatter bfFormater = new BinaryFormatter();
DataContractSerializer x = new DataContractSerializer(typeof(Image));
// Lock this method
lock (this._objLocker)
{
while (bContinue)
{
// Get the next msg
strMsgCode = srReader.ReadLine();
// Check code
switch (strMsgCode)
{
case (General.IMAGE):
{
// Read bytearray
int nSize = int.Parse(srReader.ReadLine().ToString());
byte[] btImageStream = new byte[nSize];
this._nsClient.Read(btImageStream, 0, nSize);
// Get the Stream
MemoryStream msImageStream = new MemoryStream(btImageStream, 0, btImageStream.Length);
// Set seek, so we read the image from the begining of the stream
msImageStream.Position = 0;
// Build the image from the stream
this._imgScreenImg = Image.FromStream(msImageStream); // Error Here发布于 2012-08-31 11:33:50
部分问题是您使用的是WriteLine(),它会在写入结束时添加Environment.NewLine。当您只是在另一端调用Read()时,您没有正确地处理换行符。
您要做的就是将()写到流中,然后在另一端读回它。
到字符串的转换很奇怪。
在传输图像时,您要做的是发送一个字节数组。您所需要做的就是发送预期流的长度,然后发送图像本身,然后读取另一端的长度和字节数组。
通过线路传输字节数组的最基本和最简单的方法是首先发送一个表示数组长度的整数,然后在接收端读取该长度。
一旦知道了要发送/接收多少数据,就可以在网络上以原始字节数组的形式发送数组,并读取之前在另一端确定的长度。
现在您有了原始字节和大小,您可以将缓冲区中的数组重新构造为有效的图像对象(或您刚刚发送的任何其他二进制格式)。
另外,我也不确定为什么DataContractSerializer会在那里。它是原始的二进制数据,而且您已经手动将其序列化为字节,所以这个东西没有什么用处。
使用套接字和流进行网络编程的一个基本问题是定义您的协议,因为接收端无法以其他方式知道预期的内容或流何时结束。这就是为什么每个通用协议要么有一个非常严格定义的数据包大小和布局,要么做一些像发送长度/数据对这样的事情,以便接收端知道该做什么。
如果你实现了一个非常简单的协议,比如发送一个表示数组长度的整数,并在接收端读取一个整数,那么你就完成了一半的目标。然后,发送者和接收者就下一步发生的事情达成一致。然后,发送方在线路上恰好发送该数量的字节,而接收方在线路上恰好读取该数量的字节,并认为读取已完成。您现在拥有的是接收端原始字节数组的精确副本,然后您可以随心所欲地处理它,因为您知道该数据最初是什么。
如果您需要代码示例,我可以提供一个简单的示例,否则在网上有许多示例可用。
https://stackoverflow.com/questions/12208432
复制相似问题