C#:发送和接收图像字节时出现MemoryStream问题

时间:2015-09-23 00:09:24

标签: c#

我遇到内存流问题 我正在制作鼠标程序并尝试发送图像,但是当我使用png格式将其保存到内存流中然后发送它。我只收到它的一小部分,当我使用bmp它给我一个错误(参数无效),当我使用jpeg有时我会收到缺少某些部分的图像所以请任何人帮助我吗?

服务器发送代码:(此代码应发送PC名称和图像)

string PC = Environment.MachineName + "/" + Environment.UserName+ count;
int Width = Screen.PrimaryScreen.Bounds.Width;
int Height = Screen.PrimaryScreen.Bounds.Height;
Bitmap ScreenShot = new Bitmap(Width, Height);
Graphics ScreenShotGraphics = Graphics.FromImage(ScreenShot);
ScreenShotGraphics.CopyFromScreen(0, 0, 0, 0, new Size(Width, Height), CopyPixelOperation.SourceCopy);
MemoryStream MemoryStream = new MemoryStream();
ScreenShot.Save(MemoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] ScreenShotToByte = MemoryStream.ToArray();
byte[] Image = ScreenShotToByte;
MemoryStream CollectMemoryStream = new MemoryStream();
CollectMemoryStream.Write(StringToByteArray("1"), 0, 1);
CollectMemoryStream.Write(StringToByteArray(SplitChar), 0, SplitChar.Length);
CollectMemoryStream.Write(StringToByteArray(PC), 0, PC.Length);
CollectMemoryStream.Write(StringToByteArray(SplitChar), 0,  SplitChar.Length);
CollectMemoryStream.Write(Image, 0, Image.Length);
Client.Client.Send(CollectMemoryStream.ToArray(), 0,   CollectMemoryStream.ToArray().Length, SocketFlags.None);

客户端接收代码:(此代码应接收PC名称和图像)

  

SplitText是一个字符串[]保存顺序,PC名称和图像从byte []转换为字符串并被分割

string PCName = SplitText[1];
this.Invoke((Action)(() => { int NewClientNumber = listBox1.Items.Add(PCName); }));
MemoryStream GetThumpBytes = new MemoryStream();
GetThumpBytes.Write(ByteArray, SplitText[0].Length + SplitChar.Length + SplitText[1].Length + SplitChar.Length, ByteArray.Length-(SplitText[0].Length + SplitChar.Length + SplitText[1].Length + SplitChar.Length));
byte[] ThumpBytes = GetThumpBytes.ToArray();
MemoryStream MemoryStream = new MemoryStream();
MemoryStream.Write(ThumpBytes, 0, ThumpBytes.Length);
Image Thumb = Image.FromStream(MemoryStream);
pictureBox1.Image = Thumb;

Png尝试图片: enter image description here

Jpeg尝试图片: enter image description here

Bmp尝试图片: enter image description here

1 个答案:

答案 0 :(得分:0)

我看到的一个问题是分配图像很可能是在错误的线程上。

this.Invoke(() => pictureBox1.Image = Thumb);
相关问题