Dan Bursuc
Dan Bursuc

Reputation: 15

Set an image from a class to a picturebox in a form

I have a class where I'm getting an image from a buffer and the image is set to a variable type image which will hold the image.

class MyClass
{
    public Image MyImage;
    private void ReadingCallBack(IAsyncResult ar)
    {
        Socket CurrentSocket = null;

        try
        {
            CurrentSocket = (Socket)ar.AsyncState;
            int recvsize = CurrentSocket.EndReceive(ar);
            Array.Resize(ref buffer, recvsize);
            string stream = ASCIIEncoding.ASCII.GetString(buffer);
            switch (stream.Substring(stream.IndexOf('[') + 1, stream.IndexOf(']') - 1))
            {
                case "Screenshot":

                    byte[] imgbuff = new byte[buffer.Length - 12];
                    Buffer.BlockCopy(buffer, 12, imgbuff, 0, imgbuff.Length);

                    MemoryStream ms = new MemoryStream(imgbuff);
                    MyImage = Image.FromStream(ms);

                    ms.Close();
                    break;
            }

            buffer = new byte[1024 * 5000];
            CurrentSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReadingCallBack), CurrentSocket);
        }
        catch (Exception er)
        {
            //etc
        }
    }
}

In a WindowsForm I have the following code in the constructor: The WindowsForm is called whenever the user wants to.

MyClass Class = new MyClass();
while (Class.MyImage == null)
{
    System.Threading.Thread.Sleep(1);
    Application.DoEvents();
}

pictureBox1.Image = Class.MyImage;

BUT, the image is never assigned to the picturebox, the image variable is always null.

I've checked if the image from the buffer really exists by creating an image file on my HDD with the bytes from the buffer and the image was successfully created without any issues.

What have I done wrong?

Upvotes: 0

Views: 449

Answers (2)

DonBoitnott
DonBoitnott

Reputation: 11025

I think you might be suffering from the issue of image memory being freed when it's instantiating object is disposed. Are you trapping errors in that try/catch? I'd think that when that MemoryStream object is disposed, so would be the image it was used to create.

Upvotes: 1

Janez Lukan
Janez Lukan

Reputation: 1449

Your image creation in MyClass should be in a method, and then you need to call that method with buffer as argument.

Upvotes: 0

Related Questions