Skip to content

Instantly share code, notes, and snippets.

@jpbalarini
Created November 26, 2016 15:20
Show Gist options
  • Save jpbalarini/1aa2851b57118dc8135357f4107dfa5c to your computer and use it in GitHub Desktop.
Save jpbalarini/1aa2851b57118dc8135357f4107dfa5c to your computer and use it in GitHub Desktop.
WHITELISTED_FORMATS = [
{ name: 'png', first_bytes: '89 50 4E 47 0D 0A 1A 0A' },
{ name: 'jpg1', first_bytes: 'FF D8 FF DB' },
{ name: 'jpg2', first_bytes: 'FF D8 FF E0' },
{ name: 'jpg3', first_bytes: 'FF D8 FF E1' },
{ name: 'ico', first_bytes: '00 00 01 00' },
{ name: 'gif1', first_bytes: '47 49 46 38 37 61' },
{ name: 'gif2', first_bytes: '47 49 46 38 39 61' },
{ name: 'tiff1', first_bytes: '49 49 2A 00' },
{ name: 'tiff2', first_bytes: '4D 4D 00 2A' },
{ name: 'pdf', first_bytes: '25 50 44 46' },
{ name: 'bmp', first_bytes: '42 4D' }
]
begin
file = File.open("/Users/jpb/Desktop/out.png", 'rb')
found = false
WHITELISTED_FORMATS.each do |format|
bytes_to_check = format[:first_bytes].delete(' ')
bytes_read = file.read(bytes_to_check.length / 2).unpack("H*").first.upcase
found = bytes_read == bytes_to_check
break if found
file.rewind
end
if found
puts 'File is an image'
else
puts 'File is not an image'
end
ensure
file.close if file
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment