C# 图像发送改进

c# image send improvement

我试图每秒发送尽可能多的图片并且它在本地网络上工作得很好,但是当我从朋友的计算机或其他设备上尝试时......它工作得非常慢www..我有一个非常好的互联网,我的朋友也有..我只打开了这个端口.....

我认为它可能与图像压缩或其他东西有关...

这是客户的代码

 private void startSend()
 {
    sck = client.Client;
    s = new NetworkStream(sck);

    while (true)
    {
        Bitmap screeny = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
        Graphics theShot = Graphics.FromImage(screeny);
        theShot.ScaleTransform(.25F, .25F);
        theShot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
        BinaryFormatter bFormat = new BinaryFormatter();

       bFormat.Serialize(s, screeny);

       theShot.Dispose();
       screeny.Dispose();

       Thread.Sleep(20);
   }
}

服务器是:

    public void startListening()
    {
        listener = new TcpListener(IPAddress.Any, 10);
        listener.Start();

         stream= listener.AcceptTcpClient().GetStream();

         while (true)
         {
             BinaryFormatter bFormat = new BinaryFormatter();
             Bitmap inImage = bFormat.Deserialize(stream) as Bitmap;

             theImage.Image = (Image)inImage;
         }
    }

这两种方法都在线程上工作...即使我尝试将睡眠设置为 3000 毫秒,它也非常慢....

知道我怎样才能更快地发送它吗?我对压缩一无所知,所以如果有人可以帮助大家.. :D

您可以在发送前压缩文件:

https://msdn.microsoft.com/pt-br/library/ms404280%28v=vs.110%29.aspx

尝试将这些方法添加到客户端:

byte[] Compress(byte[] b)
{
    using (MemoryStream ms = new MemoryStream())
    {
            using (GZipStream z = new GZipStream(ms, CompressionMode.Compress, true))
            z.Write(b, 0, b.Length);
        return ms.ToArray();
    }
}

byte[] ImageToByte(Image img)
{
    ImageConverter converter = new ImageConverter();
    return (byte[])converter.ConvertTo(img, typeof(byte[]));
}

将您的电话改为:

byte[] compressed = Compress(ImageToByte(screeny));
bFormat.Serialize(s, compressed);

并将这些添加到服务器:

byte[] Decompress(byte[] b)
{
    using (var ms = new MemoryStream())
    {
        using (var bs = new MemoryStream(b))
        using (var z = new GZipStream(bs, CompressionMode.Decompress))
            z.CopyTo(ms);
        return ms.ToArray();
    }
}

public static Bitmap ByteToImage(byte[] imageData)
{
    using (var ms = new MemoryStream(imageData))
    {
        return new Bitmap(ms);
    }
}

并将服务器上的 while 块内部更改为:

BinaryFormatter bFormat = new BinaryFormatter();

byte[] inBytes = bFormat.Deserialize(stream) as byte[];
Bitmap inImage = ByteToImage(Decompress(inBytes ));

theImage.Image = (Image)inImage;