固定宽高比的图像裁剪

Image cropping with fixed aspect ratio

我试图从一张 7:9 宽高比的图像中获取两组 x-y 坐标,并用 280x360 图像中的裁剪部分替换原始图像,但它不起作用。它没有抛出任何错误,但裁剪后的图像替换似乎不起作用。回显数据告诉我它吸收了所有内容,直到 imagecopyresampled 代码。

$formDatax1=$_POST["x1"];
$formDatax2=$_POST["x2"];
$formDatay1=$_POST["y1"];
$formDatay2=$_POST["y2"];

$filename='http://pathtofiles/path/photo/'.$a_photo;

$image_info = getimagesize($filename);

switch(strtolower($image_info['mime'])){
case 'image/png' : $image = imagecreatefrompng($filename); $imgtype='png'; break;
case 'image/jpeg': $image = imagecreatefromjpeg($filename); $imgtype='jpg'; break;
case 'image/gif' : $image = imagecreatefromgif($filename); $imgtype='gif'; break;
default: die();
}

$resized_width = ((int)$formDatax2) - ((int)$formDatax1);
$resized_height = ((int)$formDatay2) - ((int)$formDatay1);

$resized_image = imagecreatetruecolor(280, 360);
imagecopyresampled($resized_image, $image, 0, 0, (int)$formDatax1, (int)$formDatay1, 280, 360, $resized_width, $resized_height);

if ($imgtype=='png') {
    imagepng($resized_image, $filename);
}

if ($imgtype=='jpg') {
    imagejpeg($resized_image, $filename);
}

if ($imgtype=='gif') {
    imagejpeg($resized_image, $filename);
}

echo '<script type="text/javascript">alert("Image cropped!"); </script>';
exit();

您没有为 $filename 指定新值。 http[s] URL wrappers 可以检索文件,但不能写入。您需要指定一个本地文件系统位置来保存图像。

此解决方案来自 PHP 食谱第 3 版

使用 ImageCopyResampled() 函数,根据需要缩放图像。
按比例缩小:

$filename = __DIR__ . '/php.png';
$scale = 0.5; // Scale
// Images
$image = ImageCreateFromPNG($filename);
$thumbnail = ImageCreateTrueColor(
ImageSX($image) * $scale,
ImageSY($image) * $scale);
// Preserve Transparency
ImageColorTransparent($thumbnail,
ImageColorAllocateAlpha($thumbnail, 0, 0, 0, 127));
ImageAlphaBlending($thumbnail, false);
ImageSaveAlpha($thumbnail, true);
// Scale & Copy
ImageCopyResampled($thumbnail, $image, 0, 0, 0, 0,
ImageSX($thumbnail), ImageSY($thumbnail),
ImageSX($image), ImageSY($image));
// Send
header('Content-type: image/png');
ImagePNG($thumbnail);
ImageDestroy($image);
ImageDestroy($thumbnail);

缩小到固定大小的矩形:

// Rectangle Version
$filename = __DIR__ . '/php.png';
// Thumbnail Dimentions
$w = 50; $h = 20;
// Images
$original = ImageCreateFromPNG($filename);
$thumbnail = ImageCreateTrueColor($w, $h);
// Preserve Transparency
ImageColorTransparent($thumbnail,
ImageColorAllocateAlpha($thumbnail, 0, 0, 0, 127));
ImageAlphaBlending($thumbnail, false);
ImageSaveAlpha($thumbnail, true);
// Scale & Copy
$x = ImageSX($original);
$y = ImageSY($original);
$scale = min($x / $w, $y / $h);
ImageCopyResampled($thumbnail, $original,
0, 0, ($x - ($w * $scale)) / 2, ($y - ($h * $scale)) / 2,
$w, $h, $w * $scale, $h * $scale);
// Send
header('Content-type: image/png');
ImagePNG($thumbnail);
ImageDestroy($original);
ImageDestroy($thumbnail);