title: Object reference not set to an instance of an object. System.Drawing.Image Save
body: <p>Not sure why I am getting this error on the last line of code MyOnlineImg.Save. I am using Visual Studio 2017 on Windows 10 Pro. I am pretty sure the code used to work. When I debug it everything seems normal to me.</p>
  <pre><code>Dim MyOnlineImg As System.Drawing.Image
  MyOnlineImg = GetImagefromDB(ImgID, Now)
  Dim ms As New MemoryStream()
  Dim myImageCodecInfo As ImageCodecInfo
  Dim myEncoder As System.Drawing.Imaging.Encoder
  Dim myEncoderParameter As EncoderParameter
  Dim myEncoderParameters As EncoderParameters
  myImageCodecInfo = GetEncoderInfo(ImageFormat.Png)
  myEncoderParameters = New EncoderParameters(1)
  myEncoder = System.Drawing.Imaging.Encoder.Quality
  myEncoderParameter = New EncoderParameter(myEncoder, CType(50L, Int32))
  myEncoderParameters.Param(0) = myEncoderParameter
  MyOnlineImg.Save(ms, myImageCodecInfo, myEncoderParameters)
  </code></pre>
  <p>I also tried this but I still had the same error.</p>
  <pre><code>ms = {System.IO.MemoryStream} 
  pngCodec = {System.Drawing.Imaging.ImageCodecInfo}
  myEncoderParameters = {System.Drawing.Imaging.EncoderParameters}
  </code></pre>
  <p>Code:</p>
  <pre><code>    Dim ms As New MemoryStream()
      Dim myImageCodecInfo As ImageCodecInfo
      Dim myEncoder As System.Drawing.Imaging.Encoder
      'Dim myEncoderParameter As EncoderParameter
      'Dim myEncoderParameters As EncoderParameters
      myImageCodecInfo = GetEncoderInfo(ImageFormat.Png) 'lets think about switching from PNG to JPG to speed up performance (reduce quality)
      'myEncoderParameters = New EncoderParameters(1)
      myEncoder = System.Drawing.Imaging.Encoder.Quality
      'myEncoderParameter = New EncoderParameter(myEncoder, CType(50L, Int32))
      'myEncoderParameters.Param(0) = myEncoderParameter
  
  
      Dim pngCodec As ImageCodecInfo = GetEncoderInfo(ImageFormat.Png)
      Dim myEncoderParameters As New EncoderParameters()
      myEncoderParameters.Param(0) = New EncoderParameter(Encoder.Quality, 50)
  
      Dim MyOnlineImg As System.Drawing.Image = GetImagefromDB(ImgID, Now)
      'Dim ms As New MemoryStream()
      MyOnlineImg.Save(ms, pngCodec, myEncoderParameters)
      
  </code></pre>
  <p>I tried adding tests for nulls with breakpoints but they were all ok:</p>
  <pre><code>If ms Is Nothing Then
          Dim blah As String = &quot;&quot;
      End If
      If pngCodec Is Nothing Then
          Dim blah As String = &quot;&quot;
      End If
      If myEncoderParameters Is Nothing Then
          Dim blah As String = &quot;&quot;
      End If
  </code></pre>