You can check image formats with "Magic Numbers"
I did this test, with the help of ChatGPT =>
Class ByteArrayComparer
Implements IEqualityComparer(Of Byte())
Public Shadows Function Equals(x() As Byte, y() As Byte) As Boolean Implements IEqualityComparer(Of Byte()).Equals
Return x.SequenceEqual(y)
End Function
Public Shadows Function GetHashCode(obj() As Byte) As Integer Implements IEqualityComparer(Of Byte()).GetHashCode
Dim hash As Long = 17
For Each b In obj
hash = hash * 31 + b
Next
Return hash And &H7FFFFFFF ' truncate safely to positive 32-bit integer
End Function
End Class
Function IsSupportedImageFormat(path As String, ByRef format As String) As Boolean
format = Nothing
Dim signatures As New Dictionary(Of Byte(), String)(New ByteArrayComparer) From {
{New Byte() {&HFF, &HD8, &HFF}, "JPEG"},
{New Byte() {&H89, &H50, &H4E, &H47, &HD, &HA, &H1A, &HA}, "PNG"},
{System.Text.Encoding.ASCII.GetBytes("GIF87a"), "GIF"},
{System.Text.Encoding.ASCII.GetBytes("GIF89a"), "GIF"},
{System.Text.Encoding.ASCII.GetBytes("BM"), "BMP"},
{New Byte() {&H49, &H49, &H2A, &H0}, "TIFF (LE)"},
{New Byte() {&H4D, &H4D, &H0, &H2A}, "TIFF (BE)"},
{New Byte() {&H0, &H0, &H1, &H0}, "ICO"},
{New Byte() {&HD7, &HCD, &HC6, &H9A}, "WMF"}
}
Try
Using fs As New FileStream(path, FileMode.Open, FileAccess.Read)
Dim buffer(255) As Byte
fs.Read(buffer, 0, buffer.Length)
' Detect standard formats
For Each kvp In signatures
Dim sig = kvp.Key
Dim name = kvp.Value
If buffer.Take(sig.Length).SequenceEqual(sig) Then
format = name
Return True
End If
Next
' Detect EMF (look for EMR_HEADER at the beginning and optional " EMF" string at offset 40)
If buffer.Length >= 44 AndAlso buffer(0) = &H1 AndAlso buffer(1) = 0 AndAlso buffer(2) = 0 AndAlso buffer(3) = 0 Then
' Optional check for " EMF" at offset 40
If buffer(40) = Asc(" ") AndAlso buffer(41) = Asc("E") AndAlso buffer(42) = Asc("M") AndAlso buffer(43) = Asc("F") Then
format = "EMF"
Return True
Else
' Still likely EMF without " EMF" string
format = "EMF"
Return True
End If
End If
End Using
Catch
format = Nothing
Return False
End Try
Return False
End Function