我有通过 TCP 发送和接收图像的代码,该代码有效。然而,因为我每次都会发送整个图像,所以带宽使用量很大,并且会使我的程序在较慢的互联网连接上完全无法使用。
为了减少带宽,很明显我只想发送当前图像与前一个图像之间的差异。我希望您能为我提供一些有关如何执行此操作或使用哪些库(如果有)的信息。我在下面有我的发送和接收线程,我目前正在使用它们发送和接收图像。我的程序的用途是作为屏幕共享应用程序。
发送图像:
public void SendSS()
{
try
{
while (!mainFrm.ssStop)
{
ssTcpClient = new TcpClient();
ssTcpClient.Connect(mainFrm.contactIP, 1500);
//Set up TCP connection.
if (ssTcpClient.Connected)
{
//Connected. Capture screen image.
labelText("Connected. Now sending desktop to technician.");
Image screenShotBMP = GrabScreen();
MemoryStream ssmemStream = new MemoryStream();
screenShotBMP.Save(ssmemStream, ImageFormat.Jpeg);
NetworkStream ns = ssTcpClient.GetStream();
//Convert image to data.
byte[] bytesToSend = ssmemStream.GetBuffer();
//Store data in stream and send via port.
ns.Write(bytesToSend, 0, bytesToSend.Length);
ns.Flush();
//Dispose of image to avoid memory leakage.
screenShotBMP.Dispose();
ssTcpClient.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SendSS()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
接收图像:
public void ReceiveSS()
{
try
{
ssTcpListener = new TcpListener(IPAddress.Any, 1500);
tcpReceiver = new TcpClient();
while (!mainFrm.ssStop)
{
//Start listening for connection.
//Accept any incoming connection requests on port 1500.
ssTcpListener.Start();
tcpReceiver = ssTcpListener.AcceptTcpClient();
if (tcpReceiver.Connected)
{
//TCP connected. Receive images from contact.
labelText("Connected. Now receiving desktop from client.");
NetworkStream receivedNs = new NetworkStream(tcpReceiver.Client);
//Put image into picturebox.
Bitmap image = new Bitmap(receivedNs);
pboScrnShr.BackgroundImage = image;
receivedNs.Flush();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "ReceiveSS()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
感谢您提前提供的帮助。
最佳答案
在互联网上做了更多搜索后,我发现了这个:
Finding difference between images - By Bryan Cook 使用该代码来查找我发送的图像之间的差异(使用 snapshotBMP.Save(ssMemStream, ImageFormat.Gif),而不是 .JPEG),这当然会将内存流中的透明度保存为黑色,以便在接收时最后你必须确保(对于发送的图像差异)你确实收到了Image.MakeTransparency(Color.Black),否则如果你尝试将差异覆盖到前一个图像上,你只会得到黑屏。
我设法将接收到的图像从 12Mbps 降低到 2Mbps,但我知道对于速度较慢的连接来说,还有更多的路要走。
所有功劳都归功于 Bryan Cook 的代码,我刚刚在不同的上下文中使用了它。
关于c# - 如何比较两个不同的图像,通过tcp发送差异,然后将差异与客户端上的图像合并?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22176065/