vb.net - Display image in picturebox at runtime - Stack Overflow

时间: 2025-01-06 admin 业界

I am trying to display images in a picturebox at runtime. The images are received continuously over UDP from another host. However non of the images are getting displayed. I have tried saving the images on the disk and found that they get saved properly. The following is my code

Sub ReceiveImageContinuously()
        Dim udpClient As New UdpClient(11000)
        Console.WriteLine($"Listening for UDP packets on port {11000}...")

        Try
            While True
                Dim receivedBytes As New List(Of Byte)()

                While True
                    ' Receive a packet
                    Dim remoteEndPoint As New IPEndPoint(IPAddress.Any, 0)
                    Dim receivedChunk As Byte() = udpClient.Receive(remoteEndPoint)
                    Dim receivedMessage As String = System.Text.Encoding.UTF8.GetString(receivedChunk)

                    ' Check for termination signal
                    If receivedMessage = "END" Then
                        Console.WriteLine("Received image file termination signal.")
                        Exit While
                    End If

                    ' Add received chunk to the list
                    receivedBytes.AddRange(receivedChunk)
                    Console.WriteLine($"Received chunk of size {receivedChunk.Length}")
                End While

                ' Combine all chunks into a single byte array
                Dim completeImageBytes As Byte() = receivedBytes.ToArray()

                LoadPictureBox(completeImageBytes)
                
            End While
        Catch ex As Exception
            Console.WriteLine($"Error: {ex.Message}")
        Finally
            udpClient.Close()
        End Try
    End Sub

Public Sub LoadPictureBox(receivedBytes As Byte())
        Try
            ' Validate the received bytes
            If receivedBytes Is Nothing OrElse receivedBytes.Length = 0 Then
                Console.WriteLine("Received an empty byte array.")
                Return
            End If

            ' Use MemoryStream to create an Image from byte array
            Using ims As New MemoryStream(receivedBytes)
                ' Attempt to load the image
                Dim img As Image = Image.FromStream(ims)

                ' Check if Invoke is required
                If PictureBox1.InvokeRequired Then
                    PictureBox1.Invoke(Sub()
                                           PictureBox1.Image = img
                                           PictureBox1.Refresh()
                                       End Sub)
                Else
                    PictureBox1.Image = img
                    PictureBox1.Refresh()
                End If
            End Using

        Catch ex As Exception
            ' Log or display error message for debugging
            Console.WriteLine($"Error loading image: {ex.Message}")
            MessageBox.Show($"Error loading image: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

I have tried to save the images on the disk as follows and I found them getting saved correctly.

Dim savePath As String = Path.Combine(saveFolderPath, $"received_image_{cycle}.jpg")
File.WriteAllBytes(savePath , completeImageBytes)