Skip to content

Instantly share code, notes, and snippets.

@Freaky
Last active November 20, 2016 18:46
Show Gist options
  • Save Freaky/04db725bacabae38e602fef790540c0a to your computer and use it in GitHub Desktop.
Save Freaky/04db725bacabae38e602fef790540c0a to your computer and use it in GitHub Desktop.
IMAGE_MAGIC = {
'JPG' => 'ffd8',
'BMP' => '424d',
'TIFF-LE' => '49492a00',
'TIFF-BE' => '4d4d002a',
'GIF87a' => '474946383761',
'GIF89a' => '474946383961',
'PNG' => '89504e470d0a1a0a',
}.freeze
IMAGE_MAGIC_LEN = (IMAGE_MAGIC.values.map(&:size).max / 2.0).ceil
def identify_image_format(f)
hex = f.read(IMAGE_MAGIC_LEN).unpack('H*').first
f.rewind
IMAGE_MAGIC.each {|format, magic| return format if hex.start_with?(magic) }
return false
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment