Search code examples
c#tcpclientnetworkstreamtcpserverbinaryformatter

BinaryFormatter.Deserlize for a Bitmap rases a System.OutOfMemoryException


so .. am creating a Simple Desktop Viewer application.

but i keep getting this System.outOfMmemoryException when ever i try to de-serialize sent images through the stream.

the sending code :

 private Image getScreen() {

        Rectangle bound = Screen.PrimaryScreen.Bounds;
        Bitmap ScreenShot = new Bitmap(bound.Width,bound.Height,PixelFormat.Format32bppArgb );
        Graphics image = Graphics.FromImage(ScreenShot);
        image.CopyFromScreen(bound.X,bound.Y,0,0,bound.Size,CopyPixelOperation.SourceCopy);
        return ScreenShot;
    }
    private void SendImage() {
        BinaryFormatter binFormatter = new BinaryFormatter();
        binFormatter.Serialize(stream, getScreen());
    }

note that the images are sent using a timer that calls the SendImage() once it's started

this is my Recieving Code :

 BinaryFormatter binFormatter = new BinaryFormatter();
                Image img = (Image)binFormatter.Deserialize(stream);
                picturebox1.Image=img;

so .. whats Wrong?


Solution

  • Most likely this caused by a wrong usage of Stream. The code below is working fine:

    private Image getScreen() {
        Rectangle bound = Screen.PrimaryScreen.Bounds;
        Bitmap ScreenShot = new Bitmap(bound.Width,bound.Height,PixelFormat.Format32bppArgb );
        Graphics image = Graphics.FromImage(ScreenShot);
        image.CopyFromScreen(bound.X,bound.Y,0,0,bound.Size,CopyPixelOperation.SourceCopy);
        return ScreenShot;
    }
    private void SendImage(Stream stream) {
        BinaryFormatter binFormatter = new BinaryFormatter();
        binFormatter.Serialize(stream, getScreen());
    }
    
    void Main()
    {
        byte[] bytes = null;
        using (var ms = new MemoryStream()) {
            SendImage(ms);
            bytes = ms.ToArray();
        }
    
        var receivedStream = new MemoryStream(bytes);
        BinaryFormatter binFormatter = new BinaryFormatter();
        Image img = (Image)binFormatter.Deserialize(receivedStream);
        img.Save("c:\\temp\\test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
    }