ImageMagickを使って画像の種類を判別する

ImageMagickidentifyコマンドを使って画像の判定ができる。

拡張子はJPGと言いながら実はPNGだった例

$ identify -format %m ./path/to/image-file.jpg
PNG

特定のディレクトリ以下のすべてのファイルの種類を表示するならこんな感じ

for imagefile in $(find ./ -name *.jpg); do
  format=$(identify -format %m $imagefile)
  echo "${format} ${imagefile}"
done

jpg以外のファイルを探すならこんな感じ

for imagefile in $(find ./ -name *.jpg); do
  format=$(identify -format %m $imagefile)
  if [ $format != 'JPEG' ]; then
    echo "${format} ${imagefile}"
  fi
done

magic numberの確認

例えばカメラのRAWファイルの場合、ImageMagickはデフォルトで判別することはできない*1 どういう画像なのかはたいていマジクナンバーを見れば分かる

$ od -c ./path/to/raw-file.jpg | head -4
0000000    I   I   R   O  \b  \0  \0  \0 027  \0  \0 001 004  \0 001  \0
0000020   \0  \0 360 017  \0  \0 001 001 004  \0 001  \0  \0  \0 340  \v
0000040   \0  \0 002 001 003  \0 001  \0  \0  \0 020  \0  \0  \0 003 001
0000060  003  \0 001  \0  \0  \0 001  \0  \0  \0 006 001 003  \0 001  \0

IIRO magic number で検索するとOlympusのORFファイルだということが分かった。

参考

*1:ufrawをインストールすれば扱うことができる