LoginSignup
0
0

More than 5 years have passed since last update.

Ruby で画像の向きを補正

Last updated at Posted at 2016-05-27

ImageMagick の convert -auto-orientの挙動はやや不思議だ。EXIF 情報の Orientation 情報に従って、自動的に画像の向き(90度回転等)を補正してくれるはずなのに、なぜかそう動かない時がある。

そこで、convert -auto-orient 相当の動きを Ruby で書いてみた(要 ImageMagick)。Orientation は 1 〜 8 があるが、1はそのままの動きなので、問題ないとして、2,4,5,7 については、左右反転なので、あまりないと思って省いた。Orientationの定義を思い浮かべればそれほど難しくなく書けるはず。-strip で EXIF 情報全体を削除している。

コード

def orientation(path)
  `identify -format '%[EXIF:Orientation]' ${path}`.to_i
end

def auto_orient_options(path)
  case orientation(path)
  when 3 then "-rotate 180"
  when 6 then "-rotate 270"
  when 8 then "-rotate 90"
  end
end

def convert_auto_orient(path, new_path)
  system("convert #{auto_orient_options(path)} -strip '#{path}' '#{new_path}'")
end

convert_auto_orient("original.jpg", "reoriented.jpg")
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0