Skip to content

Instantly share code, notes, and snippets.

@kazoo04
Created June 17, 2014 11:35
Show Gist options
  • Save kazoo04/ac0612d1703865cb1330 to your computer and use it in GitHub Desktop.
Save kazoo04/ac0612d1703865cb1330 to your computer and use it in GitHub Desktop.
def valid_image?(filename)
File.open(filename, "rb") do |file|
begin
header = file.read(8)
file.seek(-12, IO::SEEK_END)
footer = file.read(12)
rescue
return false
end
# jpg
return true if filename.end_with?('.jpg') and
header[0, 2].unpack("H*") == ["ffd8"] and
footer[-2, 2].unpack("H*") == ["ffd9"]
# gif
return true if filename.end_with?('.gif') and
header[0, 3].unpack("A*") == ["GIF"] and
footer[-1, 1].unpack("H*") == ["3b"]
# png
return true if filename.end_with?('.png') and
header[0, 8].unpack("H*") == ["89504e470d0a1a0a"] and
footer[-12, 12].unpack("H*") == ["0000000049454e44ae426082"]
end
false
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment