Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.