title: Trouble cropping and resizing image
body: <p>I'm trying to create a thumbnail image for a larger image. I'm using <a href="http://deepliquid.com/content/Jcrop.html" rel="nofollow">Jcrop</a> to get the co-ordinates of the crop but I can't turn this into a properly cropped thumbnail image. I've set up Jcrop properly and it's sending through x-y co-ordinates along with the size of the box but I can't work out how to crop from that.</p>
  
  <p>What I have is the path to an image on my server, along with 4 co-ordinates and the width and height of the square box they create (I've locked the aspect ratio to 1:1 as I want square thumbnails). I then send this via Ajax to my PHP cropping script, but I cannot get it to crop the based on what is set.</p>
  
  <p>This is what I have so far:</p>
  
  <pre><code>public function Crop($file, $crop) {
  
      $height = $width = 180;
      $ratio = $width / $height;
      $pos = strrpos($file, '.');
      $name = substr($file, 0, $pos);
      $ext = strtolower(substr($file, $pos));
  
      if( ! in_array($ext, array('.gif', '.jpg', '.jpeg', '.png'))) {
          return 'INVALID_EXT';
      }
  
      // When loading the image we check to see if the first character in file is a slash, and if so remove it as the last character of root is a slash.
      $src = ROOT . (in_array(substr($file, 0, 1), array('/', '\\')) ? substr($file, 1) : $file);
      $srcRes = imagecreatefromstring(file_get_contents($src));
      if( ! $srcRes) {
          return 'INVALID_FILE';
      }
      $srcWidth = imagesx($srcRes);
      $srcHeight = imagesy($srcRes);
      $srcRatio = $srcWidth / $srcHeight;
      $dstRes = imagecreatetruecolor($crop['w'], $crop['h']);
  
      if($ext == '.gif') {
          $dstBg = imagecolorallocate($dstRes, 0, 0, 0);
          imagecolortransparent($dstRes, $dstBg);
      } elseif($ext == '.png') {
          $dstBg = imagecolorallocate($dstRes, 0, 0, 0);
          imagecolortransparent($dstRes, $dstBg);
          imagealphablending($dstRes, FALSE);
          imagesavealpha($dstRes, TRUE);
      }
  
      $srcX = 0;
      $srcY = 0;
      if($srcRatio &gt; $ratio) {
          $tmpWidth = $srcHeight * $ratio;
          $tmpHeight = $srcHeight;
          $srcX = ($srcWidth - $tmpWidth) / 2;
          $srcY = 0;
      } else {
          $tmpWidth = $srcWidth;
          $tmpHeight = $srcWidth / $ratio;
          $srcX = 0;
          $srcY = ($srcHeight - $tmpHeight) / 2;
      }
  
      imagecopyresampled($dstRes, $srcRes, 0, 0, $crop['x'], $crop['y'], $crop['w'], $crop['h'], $tmpWidth, $tmpHeight);
  
      $dst = ROOT . (in_array(substr($name, 0, 1), array('/', '\\')) ? substr($name, 1) : $name) . '-thumb' . $ext;
      if($ext == '.gif') {
          $try = imagegif($dstRes, $dst);
      } elseif($ext == '.jpg' || $ext == '.jpeg') {
          $try = imagejpeg($dstRes, $dst, 80);
      } elseif($ext == '.png') {
          $try = imagepng($newThumbImageResource, $dst);
      }
  
      if( ! $try) {
          return 'CREATE_ERR';
      }
  
      return 'SUCCESS';
  
  }
  </code></pre>
  
  <p>I've tried changing all sorts of things in <code>imagecopyresampled</code> but cannot get it to crop as per what Jcrop is sending through. If I use <code>$srcWidth</code> and <code>$srcHeight</code> it maintains the aspect ratio of the original image and squishes it into the 180px square. But it doesn't seem to be resizing it or cropping it from the right place.</p>
  
  <p>Can someone please help me work out what figures I should be using where? I've been banging my head against this all day.
  <hr>
  <strong>EDIT</strong></p>
  
  <p>Here is the rest of the code. First the JavaScript that runs JCrop. It's triggered after an Ajax file upload to create a thumbnail of that image:</p>
  
  <p>This is the Ajax function upload that at the end calls the cropper.</p>
  
  <pre><code>$(function () {
  
      'use strict';
      // Change this to the location of your server-side upload handler:
      var url = '/eshop/library/ajax/ajax.file-upload.php';
      var uploadDir = 'prodimages/';
  
      $('.listing-image').fileupload({
          url: url,
          dataType: 'json',
          autoUpload: true,
          acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
          maxFileSize: 1000000, // 1 MB
          // Enable image resizing, except for Android and Opera,
          // which actually support image resizing, but fail to
          // send Blob objects via XHR requests:
          disableImageResize: /Android(?!.*Chrome)|Opera/
              .test(window.navigator.userAgent),
          previewMaxWidth: 120,
          previewMaxHeight: 120,
          previewCrop: true,
          paramName: 'files[]',
          formData: {uploadDir: uploadDir}
      })/*.on('fileuploadprocessalways', function (e, data) {
          var index = data.index;
          var file = data.files[index];
          $(this).html(file.preview);
      })*/.on('fileuploadprogressall', function (e, data) {
          var progress = parseInt(data.loaded / data.total * 100, 10);
          $('.listing-progress', this).css(
              'width',
              progress + '%'
          );
      }).on('fileuploaddone', function (e, data) {
          var file = data.result.files[0];
          var html = '&lt;div class="listing-preview"&gt;\
              &lt;img src="' + file.thumbnailUrl + '" data-name="' + file.name + '"&gt;\
              &lt;div class="listing-preview-delete"&gt;Delete&lt;/div&gt;\
          &lt;/div&gt;';
          $(this).html(html).data('delete-url', file.deleteUrl).css('padding', 0);
  
          Crop('/' + uploadDir + file.name, $(this).prop('id'));
  
      });
  
  });
  </code></pre>
  
  <p>This sends the crop details through to the PHP script above via Ajax.</p>
  
  <pre><code>$(document).on('click', '.crop-btn', function() {
  
      var data = {
          file: $(this).data('src'),
          crop: jcrop.tellSelect()
      }
      ShowLoadingById('crop-loading');
      AjaxHandler('/eshop/library/ajax/ajax.product-crop-thumb.php', data, 'POST', true);
  
  });
  </code></pre>
  
  <p>The crop window is a lightbox, this function vertically centres it and resizes the image if it's vertically bigger than the available space.</p>
  
  <pre><code>function CentreCrop() {
  
      var m = ($(window).height() - ($('.crop &gt; div').height() + 60)) / 2;
      $('.crop &gt; div').css('margin-top', m);
  
      if($('#crop-img').height() &gt; $('.crop &gt; div').height() - 30) {
          $('#crop-img-container').height($('.crop &gt; div').height() - 30);
      }
  
  }
  </code></pre>
  
  <p>This is the initial function that stores the file to be cropped and calls the worker if it's not running.</p>
  
  <pre><code>var toBeCropped = [];
  var working = false;
  function Crop(file, id) {
  
      toBeCropped.push({path: file, id: id});
  
      if( ! working) {
          working = true;
          CropWorker();
      }
  
  }
  </code></pre>
  
  <p>This is the function I run when the crop has finished to destroy jcrop and clear the crop lightbox ready for the next image to be cropped.</p>
  
  <pre><code>function CropSuccess() {
  
      $('.crop').fadeOut(250, function() {
  
          jcrop.destroy();
          $(this).html('');
          CropWorker();
  
      });
  
  }
  </code></pre>
  
  <p>This is the worker that actually creates the content in the lightbox and initiates jcrop.</p>
  
  <pre><code>function CropWorker() {
  
      if(toBeCropped.length &gt; 0) {
          file = toBeCropped.shift();
          html = '&lt;div&gt;\
              &lt;div id="crop-img-container" class="row-fluid"&gt;\
                  &lt;img id="crop-img" src="' + file.path + '"&gt;\
              &lt;/div&gt;\
              &lt;div class="row-fluid"&gt;\
                  &lt;div class="span3 offset9"&gt;\
                      &lt;button class="span12 btn crop-btn" data-id="' + file.id + '" data-src="' + file.path + '"&gt;Create Thumb&lt;/button&gt;\
                  &lt;/div&gt;\
              &lt;/div&gt;\
              &lt;div class="row-fluid loading-screen" id="crop-loading"&gt;\
                  &lt;div&gt;\
                      &lt;h4&gt;Cropping...&lt;/h4&gt;\
                      &lt;img src="/img/loading.gif"&gt;\
                  &lt;/div&gt;\
              &lt;/div&gt;\
          &lt;/div&gt;';
          $('.crop').html(html);
          $('.crop').fadeIn(250);
          $('#crop-img').load(function() {
              CentreCrop();
              $('#crop-img').Jcrop({
                  aspectRatio: 1/1,
                  bgColor: 'black',
                  bgOpacity: 0.4,
                  boxWidth: $('#crop-img').width(), // Only just recently added boxWidth and height to see if that would fix it, no difference with or without.
                  boxHeight: $('#crop-img').height(),
                  //maxSize: [300,300],
                  minSize: [180,180]
              }, function() {
                  jcrop = this;
                  jcrop.setSelect([0,0,180,180]);
              });
          });
      } else {
          working = false;
      }
  
  }
  </code></pre>
  
  <hr>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Part of the problem it seems was the image resizing. I was changing the image size to fit the screen, I though JCrop would take care of that for me but it seems you have to tell JCrop the original dimensions of the image. I've added the true size option when initializing JCrop and it seems we're almost there.</p>
  
  <p>For smaller images, those under 1000px the cropper seems to be working great. But for larger ones (1000px +) it's producing black images. It doesn't do this when I use it with the JCrop demo script but the only difference between the two is one is outputting the file to the screen and the other is saving it. I can't see any other difference or figure out why this would happen.</p>
  
  <p><strong>UPDATE 2</strong>
  It seems to only be affected if I'm running the code through Ajax. If I run the exact same function just posting to a page and running it at the top, the thumbnail is created perfectly every time, no matter what the size of the original image or the size of the box I draw.</p>