Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP + JCrop - Cropping wrong area

Tags:

php

jcrop

I'm trying to save an cropped image with jcrop, based on x,y,w,h. I send to my PHP file, the axis x,y and width/height, but the cropped area is wrong.

this is my php function

$axis_x = $_POST["x"];
$axis_y = $_POST["y"];
$width = $_POST["w"];
$height = $_POST["h"];
$path_foto = "imgs/3.jpg";
$targ_w = $width;
$targ_h =  $height;
$jpeg_quality = 90;
$src = $path_foto;
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor($targ_w, $targ_h);

imagecopyresampled($dst_r, $img_r, 0, 0, $axis_x, $axis_y, $width, $targ_w, $targ_h, $height);

imagejpeg($dst_r, $path_foto, $jpeg_quality);

This coords is set by jcrop in an input hidden everytime when the image is redized. The problem is always crop the wrong area.

What i'm doing wrong?

like image 686
Vitor Villar Avatar asked May 28 '14 20:05

Vitor Villar


1 Answers

(Without knowing what is "wrong" with the result, it's kind of hard to help you.)

But some obvious issues you are / might be hitting:

  1. The order of your parameters in your call to imagecopyresampled() are wrong: the last 4 parameters should be $targ_w, $targ_h, $width, $height Ref

  2. "The coordinates refer to the upper left corner." Ref
    This means that y = 0 is at the top of the image, not the bottom. So if your $_POST["y"] is the number of pixels from the bottom of the image, you'll need to subtract that value from the original image's height before it will work as expected.

Taking your code, and using some hard-coded values:

<?php
$axis_x = 115;
$axis_y = 128;
$width = 95;
$height = 128;
$path_foto = "/Users/gb/Downloads/original.jpg";
$targ_w = $width;
$targ_h =  $height;
$jpeg_quality = 90;
$src = $path_foto;
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor($targ_w, $targ_h);

imagecopyresampled($dst_r, $img_r, 0, 0, $axis_x, $axis_y, $targ_w, $targ_h, $width, $height);

imagejpeg($dst_r, "/Users/gb/Downloads/cropped.jpg", $jpeg_quality);

original.jpg: original.jpg

cropped.jpg: cropped.jpg

like image 192
Guillaume Boudreau Avatar answered Oct 24 '22 05:10

Guillaume Boudreau