固定纵横比的图像裁剪


Image cropping with fixed aspect ratio

我试图以7:9的纵横比从图像中获取两组x-y坐标,并用280x360图像中的裁剪部分替换原始图像,但这不起作用。它没有出现任何错误,但裁剪后的图像替换似乎不起作用。回声数据告诉我,它需要所有的东西,直到图像复制重新采样的代码。

$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包装器可以检索文件,但不能写入。您需要指定一个本地文件系统位置来将图像保存到。

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

使用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);