<?php

require "header.php";

function autoRotateImage($image) {
    $orientation = $image->getImageOrientation();

    switch($orientation) {
        case imagick::ORIENTATION_BOTTOMRIGHT: 
            $image->rotateimage("#000", 180); // rotate 180 degrees
            break;

        case imagick::ORIENTATION_RIGHTTOP:
            $image->rotateimage("#000", 90); // rotate 90 degrees CW
            break;

        case imagick::ORIENTATION_LEFTBOTTOM: 
            $image->rotateimage("#000", -90); // rotate 90 degrees CCW
            break;
    }

    // Now that it's auto-rotated, make sure the EXIF data is correct in case the EXIF gets saved with the image!
    $image->setImageOrientation(imagick::ORIENTATION_TOPLEFT);
}

//$max_w = 250;
//$max_h = 141;
//$max_w = 350;
//$max_h = 197;
$max_w = 250;
$max_h = 350;

function showError() {
    header("Content-Type: image/png");
    readfile("img/error.png");
    exit();
}

if ( !isset($_REQUEST['id']) ) showError();
$image = new MTGImage(intval($_REQUEST['id']));
$file = "images/" . $image->getFileName();
if ( !is_file($file) ) showError();

$image = new Imagick();
$image->readImage($file);
autoRotateImage($image);

$image->thumbnailImage($max_w, $max_h, true);
$image->setImageFormat("png");
header("Content-Type: image/png");
echo $image->getImageBlob();
exit();
