Skip to content

Instantly share code, notes, and snippets.

@kan-o-ash
Last active May 30, 2016 10:49
Show Gist options
  • Save kan-o-ash/e566038044be424e2b973d0ca2fffd8b to your computer and use it in GitHub Desktop.
Save kan-o-ash/e566038044be424e2b973d0ca2fffd8b to your computer and use it in GitHub Desktop.
VALID_IMAGE_SIGNATURES = [
"\x89PNG\r\n\x1A\n".force_encoding(Encoding::ASCII_8BIT), # PNG
"GIF87a".force_encoding(Encoding::ASCII_8BIT), # GIF87
"GIF89a".force_encoding(Encoding::ASCII_8BIT), # GIF89
"\xFF\xD8".force_encoding(Encoding::ASCII_8BIT) # JPEG
].freeze
def file_is_image(temporary_file_path)
return false unless temporary_file_path
file_stream = File.new(temporary_file_path, 'r')
first_eight_bytes = file_stream.readpartial(8)
file_stream.close
VALID_IMAGE_SIGNATURES.each do |signature|
return true if first_eight_bytes.start_with?(signature)
end
false
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment