我正在为网站构建一个简单的图像裁剪实用程序。
我有一个小问题:每次我这样做时都会出现失真(我的选择坐标是粗略估计的,因此例如以错误的尺寸绘制图像)。
我画了这个草图让你明白我的意思:
这里有一些代码可以帮助您获得我想要实现的目标:
//Get the new coordinates to crop the image.
$x1 = $request->getPost('x1');
$y1 = $request->getPost('y1');
$x2 = $request->getPost('x2');
$y2 = $request->getPost('y2');
$w = $request->getPost('w');
$h = $request->getPost('h');
$croptool_width = $request->getPost('croptool_width');
$croptool_height = $request->getPost('croptool_height');
$original_width = $request->getPost('original_width');
$original_height = $request->getPost('original_height');
$infos = pathinfo($original_image_location);
$extension = strtolower($infos['extension']);
switch($extension) {
case 'gif':
$sourceImage = imagecreatefromgif($original_image_location);
break;
case 'jpg':
case 'jpeg':
$sourceImage = imagecreatefromjpeg($original_image_location);
break;
case 'png':
$sourceImage = imagecreatefrompng($original_image_location);
break;
}
// Take croptool's dimension, transpose selection coordinates to fit the original image.
$scale_y = $original_height / $croptool_height;
$scale_x = $original_width / $croptool_width;
$scaled_x1 = $x1 * $scale_x;
$scaled_y1 = $y1 * $scale_y;
$scaled_x2 = $x2 * $scale_x;
$scaled_y2 = $y2 * $scale_y;
// Crop selection and save to disk
$cropImage = imagecreatetruecolor(Model_Wineries::getCoverImageWidth(), Model_Wineries::getCoverImageHeight());
imagecopyresampled(
$cropImage, $sourceImage,
0, 0,
$scaled_x1, $scaled_y1,
Model_Wineries::getLogoImageWidth(), Model_Wineries::getLogoImageHeight(),
$scaled_x2, $scaled_y2
);
if (file_exists($cover_image_location))
unlink($cover_image_location);
imagejpeg($cropImage, $cover_image_location, 90);
chmod($cover_image_location, 0777);
if (file_exists($original_image_location))
unlink($original_image_location);
我无法弄清楚的部分是如何正确计算$scale
变量。
$croptool_width 和 $croptool_height 都是缩小后的尺寸。$original_... 是原始的。
有人可以帮我吗?
编辑:建议的反应很好,但由于某种原因,所做的一切都完全错误,请看这里:
编辑:(代码已更新)
谢谢!