【问题标题】:How to Send PictureBox image via webSocket如何通过 webSocket 发送 PictureBox 图像
【发布时间】:2014-05-22 09:53:20
【问题描述】:

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

1.) 我的第一个问题是,使用不会转换为 byte[] 或二进制的图像绘制的 PictureBox,我做错了什么?,有什么办法吗?

2.) 然后我遇到的第二个问题是,我需要将这些 byte[] 转换为字符串,以便我可以将它们与其他字符串一起发送,在接收应用程序中,我将使用拆分字符串一个分隔符,然后我将字符串转换为字节[],然后转换为图片框

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);
    }

}

请帮忙!

【问题讨论】:

    标签: c# websocket byte picturebox


    【解决方案1】:

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

    创建一个MemoryStream 并在您的Image 上调用Save 以将其保存到流中。然后,您可以在该流上调用 GetBuffer 以获取 byte 数组。通常您会传输 byte 数组,但如果您需要 string,请致电 Convert.ToBase64String

    【讨论】:

    • 感谢@jmcilhinney,帮助!
    猜你喜欢
    • 1970-01-01
    • 2015-09-15
    • 1970-01-01
    • 2019-10-15
    • 2015-03-26
    • 2017-12-09
    • 2017-11-19
    • 2013-08-26
    • 1970-01-01
    相关资源
    最近更新 更多