<?php

/**
 * Image resize
 * @param int $width
 * @param int $height
 */
$url = $_SERVER['REQUEST_URI'];


$queryString = parse_url($url, PHP_URL_QUERY);
parse_str($queryString);
$filePath = '../' . substr(parse_url($url, PHP_URL_PATH), 1);

$filename = basename($filePath);

if (isset($size)) {
    $filePath = resizeImage($size, $filename, $filePath);
}

header("Content-type: " . mime_content_type($filePath));
readfile($filePath);

exit;

function resizeImage($size, $filename, $filePath) {

    if ($size == "sm") {
        $width = 150;
        $height = 100;
    } else if ($size == "md") {
        $width = 500;
        $height = 280;
    } else if ($size == "lg") {
        $width = 640;
        $height = 480;
    }

    $dir = str_replace($filename, $size, $filePath);
    $filePath = $filePath;

    if (!is_dir($dir)) {
        mkdir($dir);
    }

    $path = str_replace($filename, $size . '/' . $filename, $filePath);


    if (file_exists($path)) {
        return $path;
    }

    /* Get original image x y */
    list($w, $h) = getimagesize($filePath);

    if ($width > $w || $height > $h) {
        return $filePath;
    }

    $src_x = $src_y = 0;
    $src_w = $w;
    $src_h = $h;

    $cmp_x = $w / $width;
    $cmp_y = $h / $height;

    // calculate x or y coordinate and width or height of source
    if ($cmp_x > $cmp_y) {
        $src_w = round($w / $cmp_x * $cmp_y);
        $src_x = round(($w - ($w / $cmp_x * $cmp_y)) / 2);
    } else if ($cmp_y > $cmp_x) {
        $src_h = round($h / $cmp_y * $cmp_x);
        $src_y = round(($h - ($h / $cmp_y * $cmp_x)) / 2);
    }


    /* read binary data from image file */
    $imgString = file_get_contents($filePath);
    /* create image from string */
    $image = imagecreatefromstring($imgString);
    $tmp = imagecreatetruecolor($width, $height);
    imagealphablending($tmp, false);

    // Create a new transparent color for image
    $color = imagecolorallocatealpha($tmp, 0, 0, 0, 127);

    // Completely fill the background of the new image with allocated color.
    imagefill($tmp, 0, 0, $color);
    imagecopyresampled($tmp, $image, 0, 0, $src_x, $src_y, $width, $height, $src_w, $src_h);

    switch (mime_content_type($filePath)) {
        case 'image/jpeg':
            imagejpeg($tmp, $path, 70);
            break;
        case 'image/jpg':
            imagejpeg($tmp, $path, 70);
            break;
        case 'image/png':
            imagepng($tmp, $path, 0);
            break;
        case 'image/gif':
            imagegif($tmp, $path);
            break;
        default:
            exit;
            break;
    }

    /* cleanup memory */
    imagedestroy($image);
    imagedestroy($tmp);
    return $path;
}

?>
