具有固定宽高比的图像裁剪

时间:2015-10-29 19:40:52

标签: php crop image-resizing

我试图从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();

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

此解决方案来自PHP cookbook 3rd edition

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