How to crop a image with php using jquery imgAreaSelect?

会有一股神秘感。 提交于 2019-12-21 04:40:53

问题


i'm using the following javascript code to instanciete jquery imgAreaSelect to crop my image.

$(document).ready(function () {
    $('#ladybug').imgAreaSelect({
        onSelectEnd: function (img, selection) {
            $('input[name="x1"]').val(selection.x1);
            $('input[name="y1"]').val(selection.y1);
            $('input[name="x2"]').val(selection.x2);
            $('input[name="y2"]').val(selection.y2);            
        }
    });
});

This relates to the following (example) html code:

<div>
    <img id="ladybug" src="ladybug.jpg" alt="" />
</div>

<div>
   <form action="#" method="post">
      <input id="x1" type="hidden" name="x1" value="" />
      <input id="y1" type="hidden" name="y1" value="" />
      <input id="x2" type="hidden" name="x2" value="" />
      <input id="y2" type="hidden" name="y2" value="" />
      <input type="submit" name="submit" value="Submit" />
   </form>
</div>

This works perfectly, i'm getting all the right information back to php when submitting the form. However, now i have to use php to modify the image by the coordinates that the form just send. And this was harder then i thought.

$image_info = getimagesize($filename);
$image = imagecreatefromjpeg($filename);

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

$resized_width = ((int)$formData["x2"]) - ((int)$formData["x1"]);
$resized_height = ((int)$formData["y2"]) - ((int)$formData["y1"]);

$resized_image = imagecreatetruecolor($resized_width, $resized_height);
imagecopyresampled($resized_image, $image, 0, 0, (int)$formData["x1"], (int)$formData["y1"], $resized_width , $resized_height, $width, $height);
imagejpeg($resized_image, $filename);

The above script works but it uses the coordinates/width/height in the wrong way. i'm always left over with a big black border in the resized image:

Can anyone set me in the right direction?


回答1:


Replacing the line that starts with imagecopyresampled with the following should do it:

imagecopyresampled($resized_image, $image, 0, 0, (int)$formData["x1"], (int)$formData["y1"], $width, $height, $width, $height);

imagecopyresampled() will take a rectangular area from src_image of width src_w and height src_h at position (src_x,src_y) and place it in a rectangular area of dst_image of width dst_w and height dst_h at position (dst_x,dst_y).



来源:https://stackoverflow.com/questions/18378545/how-to-crop-a-image-with-php-using-jquery-imgareaselect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!