0

I'm trying to stream a webcam across from a client to a server but I'm having difficulty at the conversion from the byte array back to the bitmap on the server.

Here's the code:

public void handlerThread()
{
    Socket handlerSocket = (Socket)alSockets[alSockets.Count-1];
    NetworkStream networkStream = new
    NetworkStream(handlerSocket);
    int thisRead=0;
    int blockSize=1024;
    Byte[] dataByte = new Byte[blockSize];
    lock(this)
    {
        // Only one process can access
        // the same file at any given time
        while(true)
        {
            thisRead=networkStream.Read(dataByte,0,blockSize);

            pictureBox1.Image = byteArrayToImage(dataByte);
            if (thisRead==0) break;
        }
        fileStream.Close();
    }
    lbConnections.Items.Add("File Written");
    handlerSocket = null;
}

public Image byteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream(byteArrayIn);  //here is my error
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}

At the point marked above I get "Parameter is not valid" when trying to convert back to the image and crash. Any suggestions as to what I'm doing wrong?

Tim M.
  • 53,671
  • 14
  • 120
  • 163
windowsgm
  • 1,566
  • 4
  • 23
  • 55

1 Answers1

0

Note this bit: Image.Save(..) throws a GDI+ exception because the memory stream is closed

You can create an extension method or remove the "this" for a traditional method. This looks the same as your code so I wonder if you have some type of encoding or other issue relatd to creating your underlying byte array?

public static Image ToImage(this byte[] bytes)
{
    // You must keep the stream open for the lifetime of the Image.
    // Image disposal does clean up the stream.

    var stream = new MemoryStream(bytes);
    return Image.FromStream(stream);
}
Community
  • 1
  • 1
andleer
  • 22,388
  • 8
  • 62
  • 82