vb.net image save to memory stream results in an ArgumentNullException

18,293

According to the community content for the Image.Save method, certain image formats do not have an associated encoder and fail with the error you are reporting.

Could you not use a standard format (e.g. bmp or png) when saving the file to the MemoryStream? To do this replace the call to Save with something similar to:

image.Save(ms, ImageFormat.Png)
Share:
18,293
Joel
Author by

Joel

Updated on June 04, 2022

Comments

  • Joel
    Joel almost 2 years

    In VB.NET I have the following function that allows me to calculate a hash for an image I have not yet saved to a file :

    Public Function pictureHash(ByVal image As System.Drawing.Image) As String
      Try
        If image Is Nothing Then Return Nothing
        Dim ha As HashAlgorithm = HashAlgorithm.Create()
        Dim ms As New MemoryStream()
        image.Save(ms, image.RawFormat)
        ms.Position = 0
        Dim imageHash As Byte() = ha.ComputeHash(ms)
        ms.Close()
        Return BitConverter.ToString(imageHash)
      Catch ex As Exception
        Return Nothing
      End Try
    End Function
    

    The problem is I get an ArgumentNullException on the instruction image.Save(ms, image.rawFormat).

    Here is the detail of the exception :

    System.ArgumentNullException occurred
      Message="Value cannot be null. Parameter name: encoder"
      ParamName="encoder"
      Source="System.Drawing"
      StackTrace:
           at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)
           at System.Drawing.Image.Save(Stream stream, ImageFormat format)
           at MyProgram.pictureHash(Image image)
    

    The thing is, when I look at the stack trace, the last call to Image.Save with 3 parameters (the one that crashes) isn't even made by me, but by the previous Image.Save call.

    Any idea what should I do ?

    Many thanks in advance for your help,

    Regards,

    Joël