Skip to content

Instantly share code, notes, and snippets.

@linuxenko
Forked from Freaky/identify_image_format.rb
Created November 20, 2016 18:46
Show Gist options
  • Save linuxenko/1fdb9593019147f2dfd1664ab9224498 to your computer and use it in GitHub Desktop.
Save linuxenko/1fdb9593019147f2dfd1664ab9224498 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