I have been hitting my head against a wall for the last few days. I think I might be missing something very simple?
Ok so here is the trimmed down version which reproduces the error that I am getting. I have tried to include as much detail as possible but if you would like to some other information, simply let me know.
FORM LAYOUT
I have two forms.
- Let's call them Form1andForm2.
- Form1has 2 picture boxes. Let's call them- PictureBox1and- PictureBox2.- PictureBox1has a- BackgroundImageset as shown below.
- Form2has only 1 picture box called- PictureBox1. It has no image. It looks like this
On my Form1, I have this code.
Dim data As Byte() = Nothing
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    '~~> I am doing this just for demonstration purpose. The data is actually coming
    '~~> from SQL database where the image is stored
    Dim _img As Image = PictureBox1.BackgroundImage
    Using MS As New MemoryStream()
        PictureBox1.BackgroundImage.Save(MS, PictureBox1.BackgroundImage.RawFormat)
        data = MS.GetBuffer()
    End Using
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If data IsNot Nothing Then
        Dim frm As New Form2
        With frm
            Using ms As New MemoryStream(data, 0, data.Length)
                ms.Write(data, 0, data.Length)
                '~~> Set the image of picbox#2 in form 1
                PictureBox2.BackgroundImage = Image.FromStream(ms, True)
                '~~> Set the image of picbox#1 in form 2
                .PictureBox1.BackgroundImage = Image.FromStream(ms, True)
            End Using
            .ShowDialog()
        End With
    End If
End Sub
Target Framework: 4.8.1
PROBLEM STATEMENT
If I comment out the line .PictureBox1.BackgroundImage = Image.FromStream(ms, True) which sets the image of PictureBox1 in Form2 and if I run this code, everything works fine. The PictureBox2 in Form1 get populated and the Form2 is shown with no image(obviously). However, if I uncomment the line and then run the code, I get System.OutOfMemoryException:Out of memory. as shown below.
THIS WORKS
If I use .PictureBox1.Image = Image.FromStream(ms, True), then it works just fine as shown below.
QUESTION: I would like to understand why am I getting this System.OutOfMemoryException:Out of memory. error.




