-4

I wrote this code and i get this error "Object reference not set to an instance of an object."

Private Sub SAVEASToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SAVEASToolStripMenuItem.Click
    Dim FileToSaveAs As String = System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.Temp, SaveFileDialog1.FileName)
    REM PictureBox1.Image.Save(FileToSaveAs, System.Drawing.Imaging.ImageFormat.Jpeg)
    PictureBox1.Image.Save(FileToSaveAs, System.Drawing.Imaging.ImageFormat.Jpeg)
End Sub
Kevin Brechbühl
  • 4,717
  • 3
  • 24
  • 47

2 Answers2

0

Obviously enough you have a null reference somewhere. :)

Add the following at the beginning of your method:

Debug.Assert(SaveFileDialog1 IsNot Nothing)
Debug.Assert(PictureBox1 IsNot Nothing)
Debug.Assert(PictureBox1.Image IsNot Nothing)

If any of these lines reports an object being null at runtime you'll be able to start from there to fix the problem.

Crono
  • 10,211
  • 6
  • 43
  • 75
0

The generic error in the GDI throws an error...when it cannot save a file. The two following reasons why this error occurs, when you are initializing a Bitmap object from an image stored on hard disk, it tends to create a lock on the underlying image file. Due to the lock when you try to save and overwrite your modified bitmap, it throws this error.

With that said,I would personally use an "If Statement". I ran into the same issue with this line of code below and at the very bottom is the amended fix I used to solve this problem. As a programmer, you should be able to use what I showed you from my example to fix your own. I personally tested this before posting this just to be sure. My suggestion to Crono who aided you with the problem; to try to demonstrate the same professional courtesy. The GDI error occurred from his advice and he should have helped you with it, given that fact he added to your problem.

This link is useful which touches base on the GDI error: "A generic error occurred in GDI+" when attempting to use Image.Save

'BEFORE:
 For Each img As Image In 
 GetImagesFromURL("https://moviestowatch.tv/movie")
            Try               
                    img.Save(filename:=$"{portfolio}{i}.png")
                    i += 1
                End If
            Catch ex As Exception
                'when it's done it gives an error telling us that there is no image in the next img, so we stop
                Exit For
            End Try

        Next

'Method used to correct the issue:
  AFTER:
  For Each img As Image In 
  GetImagesFromURL("https://moviestowatch.tv/movie")
            Try
     HERE: >>>> If img IsNot Nothing Then
                    img.Save(filename:=$"{portfolio}{i}.png")
                    i += 1
                End If
            Catch ex As Exception
                'when it's done it gives an error telling us that there is no image in the next img, so we stop
                Exit For
            End Try

        Next