<?php
$debug=true;
$debug=false;

$url = $_GET["url"]; 
$width = isset($_GET["width"]) && is_numeric($_GET["width"]) ? $_GET["width"] : 0;
$height = isset($_GET["height"]) && is_numeric($_GET["height"]) ? $_GET["height"] : 0;

if ($height == 0 && $width == 0) {
  $height = 500;
}

$width = max(0, $width);
$height = max(0, $height);
if ($height > 0 && $width > 0) {
  $ratio = $width / $height;
}

if ($debug) {
  header('Content-Type: text/plain');
  echo "url=$url\n";
  echo "\n";
  echo "height=$height\n";
  echo "width=$width\n";
  echo "ratio=$ratio\n";
  echo "\n";
}

if (preg_match("/jpg$/i", $url) || preg_match("/jpeg$/i", $url)) {
  $src = imagecreatefromjpeg($url);
} else if (preg_match("/png$/i", $url)) {
  $src = imagecreatefrompng($url);
} else {
  header("Content-Type: text/plain");
  echo "Unsupported file type: $url";
  http_response_code(400);
  exit(0);
}

if ($src == FALSE) {
  header("Content-Type: text/plain");
  echo "Couldn't open $url";
  http_response_code(404);
  exit(0);
}

$width_orig = imageSX($src);
$height_orig = imageSY($src);

$ratio_orig = $width_orig / $height_orig;

if (isset($ratio)) {
  if ($ratio > $ratio_orig) {
    $width = $height * $ratio_orig;
  } else {
    $height = $width / $ratio_orig;
  }
} else if ($width > 0) {
  $height = $width / $ratio_orig;
} else {
  $width = $height * $ratio_orig;
}

$width = round($width);
$height = round($height);

if ($debug) {
  header('Content-Type: text/plain');
  echo "height=$height\n";
  echo "width=$width\n";
  echo "width_orig=$width_orig\n";
  echo "height_orig=$height_orig\n";
  echo "ratio_orig=$ratio_orig\n";
  echo "\n";
  return 0;
}

$dst = imagecreatetruecolor($width, $height);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); 
imagedestroy($src);

header('Content-Type: image/jpeg');
imagejpeg($dst);
imagedestroy($dst);
?>
