Bitmap Conversion

怎甘沉沦 提交于 2020-01-07 08:28:24

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/13696438/bitmap-conversion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!