普段carrierwave と RMagickを使って画像をアップロードしてるんですけど、
時間があったんでorientation情報の影響で勝手に回転してしまう問題を解決しました
javaだとこんな感じですが、回転や反転を直してやることで表示したときに画像の向きが「おかしい」といった問題を対処することができます
private static final int NONE = 0;
private static final int HORIZONTAL = 1;
private static final int VERTICAL = 2;
private static final int[][] OPERATIONS = new int[][] {
new int[] { 0, NONE},
new int[] { 0, HORIZONTAL},
new int[] {180, NONE},
new int[] { 0, VERTICAL},
new int[] { 90, HORIZONTAL},
new int[] { 90, NONE},
new int[] {-90, HORIZONTAL},
new int[] {-90, NONE},
};
public static MagickImage rotateByExif(MagickImage image) throws MagickException {
try {
int index = Integer.parseInt(image.getImageAttribute("EXIF:Orientation")) - 1;
int degrees = OPERATIONS[index][0];
if (degrees != 0)
image = image.rotateImage(degrees);
switch (OPERATIONS[index][1]) {
case HORIZONTAL:
image = image.flopImage();
break;
case VERTICAL:
image = image.flipImage();
}
}
catch (NumberFormatException exc) {}
catch (NullPointerException exc) {}
return image;
}
javaみたいにコードを書いていってもいいんでしょうけど、RMagickには auto_orient
という便利なメソッドがあるのでそちらを使うと、簡単に実装できます!
class PostImageUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def cache_dir
"#{Rails.root}/tmp/uploads"
end
def extension_white_list
%w(jpg jpeg gif png)
end
# ここでorientationの問題を解消しています
def auto
manipulate! do|image|
image.auto_orient
end
end
# ここも追加
process :auto
process :resize_to_limit => [850, 600]
version :thumb do
process :resize_to_fit => [400, 400]
end
end
orientationの問題を解決するコード・記事は様々な種類があると思いますが、
今回実装したこのメソッドが一番シンプルなのではないかと思います
あと、process :auto を加えていますが、だたメソッドを定義しただけでは
実行されないようです
下記リンクにorientationテスト用画像のページがありますので、そちらを利用すると結構捗ります!
Rotate images according to EXIF info
こちらのリンクにはorientation1 ~ 8 までの画像があります↓
Rotating images doesn’t adjust orientation for imagick

コメントを残す