LoginSignup
9
8

More than 5 years have passed since last update.

画像が回転されてアップロードされてしまうのをImagickで直す

Posted at

iPhoneでアップロードしたファイルが90度回転した向きで表示されてしまう…というので調べたら、Exifにorientationの情報があるのですが、アップロード時にExifを削除して保存するようにしていたからのようでした。
Exifを残した状態でも、見る人の環境によって回転して表示されたりされなかったりなようなので、サーバー側で正しい向きに回転して保存するようにしました。

$im = new Imagick($filePath);
$orientation = $im->getImageOrientation();
switch ($orientation) {
    case 2: // Mirror horizontal
        $im->flopImage();
        break;
    case 3: // Rotate 180
        $im->rotateImage('#000000', 180);
        break;
    case 4: // Mirror vertical
        $im->flipImage();
        break;
    case 5: // Mirror horizontal and rotate 270
        $im->flopImage();
        $im->rotateImage('#000000', 270);
        break;
    case 6: // Rotate 90
        $im->rotateImage('#000000', 90);
        break;
    case 7: // Mirror horizontal and rotate 90
        $im->flopImage();
        $im->rotateImage('#000000', 90);
        break;
    case 8: // Rotate 270
        $im->rotateImage('#000000', 270);
        break;
}
$im->stripImage();
$im->writeImage($filePath);

Exif消さない場合は、stripImage()のかわりにsetImageOrientation(1)をすればいいはず。きっと。

本当はORIENTATION 定数で書きたいんだけど、TOPLEFTとかよくわからないんだよな…。

9
8
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
9
8