PHP + JCrop - Cropping wrong area
Asked Answered
T

1

7

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?

Toland answered 28/5, 2014 at 20:43 Comment(3)
php.net/manual/en/function.imagecopyresampled.php imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); Try imagecopyresampled($dst_r, $img_r, 0, 0, $axis_x, $axis_y, $targ_w, $targ_h, $width, $height);. (Notice the $width variable was moved down the line.)Randers
I try this to, but don't work.Toland
What values are you getting in the PHP function for the $_POST vars?Randers
O
1

(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

Outroar answered 2/9, 2018 at 20:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.