title: Compress & save base64 image
body: <p>My app is receiving base64-encoded image-files from the webbrowser. I need to save them on the client. So I did:</p>
  
  <pre><code>$data = base64_decode($base64img);
  $fileName = uniqid() . '.jpg';
  file_put_contents($uploadPath . $fileName, $data);
  return $fileName;
  </code></pre>
  
  <p>Which works fine.</p>
  
  <p>Now I need to compress &amp; resize the image to max. 800 width &amp; height, maintaining the aspect-ratio.</p>
  
  <p>So I tried:</p>
  
  <pre><code>$data = base64_decode($base64img);
  $fileName = uniqid() . '.jpg';
  file_put_contents($uploadPath . $fileName, $data);
  return $fileName;
  </code></pre>
  
  <p>which does not work (error: "imagejpeg() expects parameter 1 to be resource, string given").
  And of course, this does compress, but not resize.</p>
  
  <p>Would it be best to save the file in /tmp, read it and resize/move via GD? </p>
  
  <p>Thanks.</p>
  
  <p><strong>2nd part</strong></p>
  
  <p>Thanks to @ontrack I know now that</p>
  
  <pre><code>$data = imagejpeg(imagecreatefromstring($data),$uploadPath . $fileName,80);
  </code></pre>
  
  <p>works. </p>
  
  <p>But now I need to resize the image to max 800 width and height. I have this function:</p>
  
  <pre><code>function resizeAndCompressImagefunction($file, $w, $h, $crop=FALSE) {
      list($width, $height) = getimagesize($file);
      $r = $width / $height;
      if ($crop) {
          if ($width &gt; $height) {
              $width = ceil($width-($width*($r-$w/$h)));
          } else {
              $height = ceil($height-($height*($r-$w/$h)));
          }
          $newwidth = $w;
          $newheight = $h;
      } else {
          if ($w/$h &gt; $r) {
              $newwidth = $h*$r;
              $newheight = $h;
          } else {
              $newheight = $w/$r;
              $newwidth = $w;
          }
      }
      $src = imagecreatefromjpeg($file);
      $dst = imagecreatetruecolor($newwidth, $newheight);
      imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
      return $dst;
  }
  </code></pre>
  
  <p>So I thought I could do:</p>
  
  <pre><code>$data = imagejpeg(resizeAndCompressImagefunction(imagecreatefromstring($data),800,800),$uploadPath . $fileName,80);
  </code></pre>
  
  <p>which does not work.</p>