Validating a file header (PNG)

Long story, but I need to validate that a file is indeed a PNG.

I’ve tried several different permutations, but the signature check always fails. I tried the signature both as a plain string and as a memory block. I think the issue might with the encoding with which the BinaryStream.read method string is returned, but I’m kind of guessing there.

Any hints ?

[code]
validatePNG( filename as string ) as string
// dim signature as string = chr(&h89) + “PNG” + chr( &h0d ) + chr( &h0a ) + chr( &h1a ) + chr( &h0a )

dim signature as new MemoryBlock(8)
signature.Byte(0) = &h89
signature.Byte(1)= &h50
signature.Byte(2)= &h4e
signature.Byte(3)= &h47

signature.Byte(4) =&h0d
signature.Byte(5)= &h0a
signature.Byte(6)= &h1a
signature.Byte(7)= &h0a

dim f as FolderItem = new FolderItem(filename)
if f <> nil and f.Exists then
dim readstream as BinaryStream
try
readstream = BinaryStream.Open(f)
dim buffer as string = readstream.Read(8, Encodings.ASCII)
readstream.close
if buffer.Mid(1,8) <> signature.mid(1,8) then // <— The strings never match
return “notpng”
end
catch e as IOException
readstream.close
return “notpng”
end
end

Return filename[/code]

See this recent thread :
https://forum.xojo.com/17942-need-help-identifying-picture-format

Try StrComp.

if StrComp( buffer, signature.StringValue( 0, 8 ), 0 ) = 0 then ...

But when you look in the debugger, do the bytes match?

Thanks Michel, that post indeed contained the information I was looking for. Works great now!

Thanks Kem. The file I’m testing is indeed a valid png and the bytes did match. Not sure which my approach failed, and I will keep yours in mind.

Thanks all!

it would be valid if PNGPictureMBS class can read it and issues no warning/error message.