<?php
if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
  $storrelse = (isset($_POST['storrelse']) && $_POST['storrelse'] <= 1000 && is_numeric($_POST['storrelse']))?$_POST['storrelse']:100;
  if ($_FILES['bildet']['error'] != UPLOAD_ERR_OK) {
    header('Content-type: text/plain');
    echo 'Opplastingsfeil. Prøv igjen';
    print_r($_FILES);
  }
  header('Content-type: image/jpg');

  if (is_file($_FILES['bildet']['tmp_name'])) {
    $bilde = file_get_contents($_FILES['bildet']['tmp_name']);
    $img = imagecreatefromstring($bilde);
    if ($img) {
      $width        = ImageSX($img);
      $height       = ImageSY($img);
      $ratio        = $width/$storrelse;
      $newWidth     = $storrelse;
      $newHeight    = $height / $ratio;
      $newImage=ImageCreateTrueColor($newWidth, $newHeight);
      ImageCopyResampled ($newImage,
                          $img, 0, 0, 0, 0,
                          $newWidth,
                          $newHeight,
                          $width,
                          $height);
      $token = md5(uniqid(rand(), true));
      ImageJPEG($newImage, 'temp/'.$token.'.jpg', 80);
      header('Location: http://www.gildseth.com/temp/'.$token.'.jpg');
      exit;
    }
  } else {
    header('Content-type: text/plain');
    echo 'Opplastingsfeil. Prøv igjen';
  }
}
?>
<html>
  <head>
    <title>Bildeforminsker</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  </head>
  <body>
  <form enctype="multipart/form-data" action="bildeforminsker.php" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="15000000" />
    <label>
      Velg bilde (Maks 15MB)<br />
      <input name="bildet" type="file" onchange="document.getElementById('bilde').innerHTML = '&lt;img src=&quot;file:///' + this.value + '&quot; width=200/&gt; '" />
    </label><br/>
    <label>
      Bredde<br/>
      <select name="storrelse">
        <option>100</option>
        <option>200</option>
        <option>300</option>
        <option>400</option>
        <option>500</option>
        <option>600</option>
        <option>700</option>
        <option>800</option>
        <option>900</option>
        <option>1000</option>
      </select>px
    </label><br/><br/>
    <input type="submit" value="Forminsk" />
  </form>
  Forhåndsvisning:<br/>
  <div id="bilde" style="height: 400px; width: 500px;">&nbsp;</div>

  </body>
</html>
