如何通过webSocket发送PictureBox图像

本文关键字:PictureBox 图像 发送 webSocket 何通过 | 更新日期: 2023-09-27 18:04:35

我需要一些帮助这段代码。我正在捕获桌面屏幕并在PictureBox中显示它,这很好,但我正试图将该PictureBox图像转换为字节[],然后转换为字符串,这样我就可以通过WebSocket (ws)发送它。

1)。我的第一个问题是,用图像绘制的PictureBox不会转换成字节[]或二进制,我在那里做错了什么?还有别的办法吗?

2)。第二个问题是,我需要将这些byte[]转换为字符串这样我就可以将它们与其他字符串一起发送,在接收应用程序中,我将使用分隔符分割字符串,然后将字符串转换为byte[]然后转换为picturebox

WebSocket ws;
// Here goes the rest of the websocket code, which it works just fine.
private void Display(Bitmap desktop)
{
    Graphics g;
    Rectangle r;
    if (desktop != null)
    {
        // Here I'm capturing the desktop screen and filling the PictureBox1 with it.
        r = new Rectangle(0, 0, PictureBox1.Width, PictureBox1.Height);
        g = PictureBox1.CreateGraphics();
        g.DrawImage(desktop, r);
        g.Flush();
        // Here I'm trying to convert the filled PictureBox into Byte[]
        ImageConverter converter = new ImageConverter();
        byte[] imageBytes = (byte[])converter.ConvertTo(PictureBox1.Image, typeof(byte[]));
        // Here I'm trying to conver the byte[] into a string text
        string bytesString1 = System.Text.Encoding.ASCII.GetString(imageBytes);
        string firstString = "1504";
        string separator = "+";
        // Here I'm sending the message via Websocket, which includes the "firstString",
        // the "separator" so then we can use Split in the receiving application, and 
        // then the "bytesString1" which contains the image data.
        string messageToSend = firstString + separator + bytesString1;
        ws.Send(messageToSend);
    }
}

请帮忙!

如何通过webSocket发送PictureBox图像

不要将Bitmap绘制到PictureBox上,而是将其分配给Image属性。如果必须使用GDI+将Bitmap绘制到PictureBox上,则必须将Bitmap存储在某个地方以供以后使用。无论哪种方式,您都需要一个Image对象(注意Bitmap继承了Image)。

创建MemoryStream并在Image上调用Save以将其保存到流。然后,您可以在该流上调用GetBuffer以获得byte数组。一般来说,您将传输byte数组,但如果您需要string,则调用Convert.ToBase64String