使用JS和PHP裁剪和旋转图像


Crop and rotate images with JS and PHP

我在google上搜索了几天,除了Kroppr我什么也没找到,但是我不能承诺使用一个在部署前不能在本地测试的工具。

我所需要的是能够为用户提供裁剪和旋转图像的工具,并让服务器保存它,覆盖原始图像。似乎有很多裁剪工具,但没有一个可以旋转。

有这样的工具吗?

还没有人回答这个问题吗?嗯,好吧,我想你将很难找到一个工具,正是你喜欢的。我猜你正在寻找类似于Kroppr的东西,但不是与服务相关的东西。

所以这里有一些资源,你可以用它来构建一个!

http://code.google.com/p/jqueryrotate/

http://raphaeljs.com/

这两个看起来都是非常可靠的库,可以让你旋转图像。

与裁剪器一起使用。显示图像的样子。

现在是狡猾的部分。你只需要记住两件事。

1)选择旋转角度0-360

2)作物的x1, y1, x2, y2。

收集了这些数据后,调用服务器上的php脚本并将图像处理(角度,x1, y1, x2, y2)的值传递给它,这可以通过ajax,表单提交通过POST完成,或者您甚至可以使用GET并直接将它们作为URL中的变量发送

现在使用GD在PHP中执行所有的图像操作。

<?php
//Incoming infomation. This should be set by $_GET[] or $_POST[] rather than the hardcoded examples.
$x1 = 100;
$y1 = 100;
$x2 = 400;
$y2 = 400;
$degrees = 47;
$filename = 'images/ducks.jpeg';
//find the original image size
$image_info = getimagesize($filename);
$original_width = $image_info[0];
$original_height = $image_info[1];
//calculat what the new image size should be.
$new_width = abs($x2 - $x1);
$new_height = abs($y2 - $y1);

$image_source = imagecreatefromjpeg($filename);
//rotate
$rotate = imagerotate($image_source, $degrees, 0);
//rotating an image changes the height and width of the image.
//find the new height and width so we can properly compensate when cropping.
$rotated_width = imagesx($rotate);
$rotated_height = imagesy($rotate);
//diff between rotated width & height and original width & height
//the rotated version should always be greater than or equal to the original size.
$dx = $rotated_width - $original_width;
$dy = $rotated_height - $original_width;
$crop_x = $dx/2 + $x1;
$crop_y = $dy/2 + $y1;

$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_image, $rotate, 0, 0, $crop_x, $crop_y, $new_width, $new_height, $new_width, $new_height);
//save over the old image.
imagejpeg($new_image, $filename);
?>

这只是一个简单的例子,让你去解决。如果您希望这对jpeg以外的图像类型也有效,则需要进行一些检查,并使用GD的其他方法来处理.png或.gif。旋转和裁剪代码将保持不变。

现在剩下的大部分修补工作都在前端,我将把它留给你来决定。所有你需要捕获的是一个旋转角度和x,y裁剪点。

希望这是有帮助的。如果你在前端方面需要更多的帮助,请告诉我。

注。我想发布更多的资源链接,但显然我只允许发布2个,因为我的声誉还不够高。

上面的答案真的很好,但是你可以看看

http://phpthumb.sourceforge.net/-用于裁剪

http://code.google.com/p/jqueryrotate/- jQuery旋转(上贴)

这两个在我所有的项目中都很好用

我还发现了另一种使用javascript裁剪图像并让服务器影响更改的方法。请在git上查看这个项目。我仍然在测试它,不过,我将很快提供一些代码片段,只要我得到它完美。图像收割机