C#通过套接字发送图像

时间:2013-09-02 18:18:51

标签: c# image sockets

我正在尝试通过连接到服务器的套接字发送屏幕截图,但是我得到了异常(在服务器窗口上):参数无效,这里是代码: 客户方:

public static Image CaptureDesktop()
    {
        Rectangle bounds = default(Rectangle);
        System.Drawing.Bitmap screenshot = null;
        Graphics graph = default(Graphics);
        bounds = Screen.PrimaryScreen.Bounds;
        screenshot = new Bitmap(bounds.Width, bounds.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        graph = Graphics.FromImage(screenshot);
        graph.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy);
        return screenshot;
    }
    public static void PrepareImage()
    {
        Bitmap bmp = new Bitmap(CaptureDesktop());
        Image f = (Image)bmp;
        MemoryStream ms = new MemoryStream();
        f.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        _clientSocket.Send(ms.ToArray());
        Console.WriteLine("data sent");

    }

服务器端:

public static Image byteArrayToImage(byte[] byteArrayIn)
    {
        MemoryStream ms = new MemoryStream(byteArrayIn);
        Image returnImage = Image.FromStream(ms);
        return returnImage;
    }
    private void ReceiveCallback(IAsyncResult AR)
    {
        Socket current = (Socket)AR.AsyncState;
        int received = 0;

        try
        {
            received = current.EndReceive(AR);
        }
        catch (SocketException)
        {
            current.Close(); // Dont shutdown because the socket may be disposed and its disconnected anyway
            _clientSockets.Remove(current);
            return;
        }

        byte[] recBuf = new byte[received];
        Array.Copy(_buffer, recBuf, received);
        try
        {
            pictureBox1.Image = byteArrayToImage(recBuf);
        }
        catch (Exception a)
        {
            MessageBox.Show(a.Message);
        }


    }

异常在此行​​:Image returnImage = Image.FromStream(ms);

我的代码有什么问题? 谢谢:))

0 个答案:

没有答案