在 php 中裁剪图像


Image cropping in php

所以我正在尝试编写一个小脚本来裁剪用户图像。我会将一些信息(宽度、高度、对齐属性和图像 url)发送到脚本,它应该返回裁剪后的图像。但是,它不起作用...只是一个"找不到图像"符号:/这是我的剧本,有什么想法吗?

<?php
session_start();
header('Content-type: image/jpeg');
$w=$_GET['w'];
$h=$_GET['h'];
$x=$_GET['x'];
$y=$_GET['y'];
$filename="http://www.domain.com/".$_GET['src'];
$file_ext = substr($filename, strrpos($filename, ".") + 1);
$ext='';
if($file_ext=='jpg')
{
    $image = imagecreatefromjpeg($filename); 
}
else if ($file_ext=='gif')
{
    $image = imagecreatefromgif($filename); 
}
else if ($file_ext=='png')
{
    $image = imagecreatefrompng($filename); 
} 
$crop = imagecreatetruecolor($w,$h);
imagecopy($crop, $image, 0, 0, $x, $y, $w, $h);
imagejpeg($crop);
?>

编辑:看起来这是错误:致命错误:在第 24 行的域路径/裁剪中调用未定义的函数 imagecreatetruecolor(.php我需要做什么来加载这个函数吗?

根据你对错误的评论,imagecreatetruecolor() 确实是一个函数,但前提是你加载了 GD 库。

请确保您的 PHP 安装具有兼容的 GD 版本,如果您刚刚添加了 Web 服务器,请不要忘记重新启动它。

使用 ImageMagick,试试这个;

<?php
function resize_image($file, $w, $h, $crop=FALSE) {
    $img = new Imagick($file);
    if ($crop) {
        $img->cropThumbnailImage($w, $h);
    } else {
        $img->thumbnailImage($w, $h, TRUE);
    }
    return $img;
}
resize_image(‘/path/to/some/image.jpg’, 150, 150);

我建议你使用imagemagick而不是GD/GD2 lib。如果你追求质量,ImageMagick太好了。有这个链接,它也给出了相同的比较http://www.rubblewebs.co.uk/imagemagick/compair.php