C#BinaryFormatter.Deserialize to Image

时间:2016-01-12 03:09:06

标签: c# sockets

我正在尝试通过C#中的TcpClient接收图像,我遇到麻烦反序列化图像并将其放入Windows窗体的图片框中,我是否遗漏了一些明显的或者根本不可能的东西?我最初在Visual Basic中创建了代码,现在我正在尝试将其转移到C#。 这是我的Visual Basic版本,完全正常:

Private Sub ReceiveImage()

    Dim bf As New BinaryFormatter
    While client.Connected = True
        Try
            ns = client.GetStream
            PictureBox1.Image = bf.Deserialize(ns)
        Catch ex As Exception
            MsgBox("Client disconnected!")
        End Try

    End While

End Sub

我的C#版本是这样的:

    public static void ReceiveImage()
    {

        BinaryFormatter bf = new BinaryFormatter();
        while (client.Connected)
        {

            try
            {
                ns = client.GetStream();
                self.pictureBox1.Image = bf.Deserialize(ns);
                //                          ^Error here
            }
            catch (Exception ex)
            {



            }
        }

    }

将鼠标悬停在错误上时,我得到的完整错误是Cannot implicitly convert type 'object' to 'System.Drawing.Image'. An explicit conversion exists. Are you missing a cast?

1 个答案:

答案 0 :(得分:0)

您需要转换BinaryFormatter

返回的对象
self.pictureBox1.Image = (System.Drawing.Image)bf.Deserialize(ns);

如果您需要有关如何使用C#进行投射的解释,您可以查看:Casting and Type Conversions