ImageSpiderに使った、画像ファイルの内容から適切な拡張子の文字列を得るコード、載せておきます。Rubyですけど何にでも書き換えられると思います。
# 画像ファイルの内容から適切な拡張子の文字列を得る
# 不明な場合は空文字列を返す
# '.bmp' '.gif' '.jpg' '.png' '.psd' '.tif' に対応
# WBMP, JPEG 2000, PICT 等は
# ヘッダでの判定が複雑そうなのと一般的ではないことから割愛
#
# [data] 画像ファイルの内容(String)
def get_image_ext(data)
bytes = []
index = 0
data.each_byte {|b|
bytes.push(b)
index += 1
break if index >= 8
}
if bytes[0, 2] == [0x42,0x4D]
return '.bmp'
elsif bytes[0, 6] == [0x47, 0x49, 0x46, 0x38, 0x37, 0x61]
return '.gif'
elsif bytes[0, 6] == [0x47, 0x49, 0x46, 0x38, 0x39, 0x61]
return '.gif'
elsif bytes[0, 3] == [0xFF, 0xD8, 0xFF]
return '.jpg'
elsif bytes[0, 8] == [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
return '.png'
elsif bytes[0, 4] == [0x38, 0x42, 0x50, 0x53]
return '.psd'
elsif bytes[0, 4] == [0x49, 0x49, 0x2A, 0x00]
return '.tif'
elsif bytes[0, 4] == [0x4D, 0x4D, 0x00, 0x2A]
return '.tif'
end
return ""
end
参考サイト:
- http://hpcgi1.nifty.com/MADIA/VBBBS2/wwwlng.cgi?print+200803/08030026.txt
- http://sadoyama.sakura.ne.jp/world/htm/note/002_05_psd.htm
- http://sadoyama.sakura.ne.jp/world/htm/note/002_09_tif.htm#kousei
…コード載せる用の機能とかないんかなぁ。はてなブログは。