Search code examples
phpjqueryajaxjcrop

Php image cropping


I'm trying to crop an image using the 'jcrop' library, and after sending coords to server in ajax. When applying changes to the image in PHP I do not get the selected area but something not regular; sometimes a zoom of the image and sometimes a different area cropping.

I would appreciate any suggestion, because I'm working on this since two days and slowly becoming crazy!

Thanks :)

PHP

<?php
  header('Access-Control-Allow-Origin: *');
  //header('Content-Type: image/jpeg');

  $x1 = $_POST['x1'];
  $y1 = $_POST['y1'];
  $x2 = $_POST['x2'];
  $y2 = $_POST['y2'];
  $nw = $_POST['nw']; // new width
  $nh = $_POST['nh']; // new height

  $src = './uploads/hello.jpeg';

  $image = @imagecreatefromjpeg($src) 
        or die('error imagecreatefromjpeg()');

  $width = imagesx($image);
  $height = imagesy($image);

  $cropped = @imagecreatetruecolor($nw, $nh) 
        or die('error imagecreatetruecolor()');

  $result = @imagecopyresampled($cropped, $image, 0, 0, $x1, $y1, $nw, $nh, $width, $height) 
        or die("error imagecopyresampled()");

  // save image
  imagejpeg($cropped, 'test.jpeg', 100);    
?>

jQuery

$(document).ready(function () {
    var x1, y1, x2, y2, nw, nh;
    var width = $('#image').prop('naturalWidth');
    var height = $('#image').prop('naturalHeight');
    function updateCoords(a) {
        x1 = a.x;  y1 = a.y;
        x2 = a.x2; y2 = a.y2;
        nw = a.w;  nh = a.h;
    }
    $('#image').Jcrop({
        trueSize: [width, height],
        onSelect: updateCoords,
        onChange: updateCoords,
        boxWidth: width,
        boxHeight: height
    });
    $('#button').click(function (e) {
        e.preventDefault();
        $.ajax({
           url: 'http://webaddress/server/crop.php',
           type: 'POST',
           crossDomain: true,
           data: {
              x1: x1, y1: y1,
              x2: x2, y2: y2,
              nw: nw, nh: nh
           }
        }).done(function (response) {
              console.log("Server:\n" + response);
        });
    });
});

HTML

<img id="image" src="hello.jpeg" alt="image"/>
<button id="button">Crop</button>

Solution

  • In your case you used incorrect function. imagecopyresampled can change size of image.

    For crop function best choice is imagecopy

    Just try change to this

    $result = @imagecopy($cropped, $image, 0, 0, $x1, $y1, $nw, $nh) 
        or die("error imagecopy()");
    

    Manual for function imagecopy