【问题标题】:How to crop image using GD image functions如何使用 GD 图像函数裁剪图像
【发布时间】:2011-09-02 21:19:43
【问题描述】:

我的代码中的所有内容都非常适合创建上传图片的缩略图。

现在我需要做的就是将图像中心的 $thumb 裁剪成正方形 (50x50)

这是我目前的功能

    $ext = end(explode('.', $_FILES['profile_photo']['name']));

    if ($ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif')
    {
        $tmp = $_FILES['profile_photo']['tmp_name'];

        if ($ext=='jpg' || $ext=='jpeg')
            $src = imagecreatefromjpeg($tmp);
        else if ($ext=='png')
            $src = imagecreatefrompng($tmp);
        else 
            $src = imagecreatefromgif($tmp);

        list($width,$height) = getimagesize($tmp);

        $thumb_width = 50;
        $thumb_height = ($height/$width) * $thumb_width;
        $thumb_tmp = imagecreatetruecolor($thumb_width, $thumb_height);

        $full_width = 200;
        $full_height = ($height/$width) * $full_width;
        $full_tmp = imagecreatetruecolor($full_width, $full_height);

        imagecopyresampled($thumb_tmp, $src, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height);         
        imagecopyresampled($full_tmp, $src, 0, 0, 0, 0, $full_width, $full_height, $width, $height);        

        imagejpeg($thumb_tmp, 'images/profile/'.$user['id'].'_'.time().'_thumb.'.$ext, 100);
        imagejpeg($full_tmp, 'images/profile/'.$user['id'].'_'.time().'_full.'.$ext, 100);

        imagedestroy($src);
        imagedestroy($thumb_tmp);
        imagedestroy($full_tmp);

        // delete old image from server if it is not none.png
    }

任何帮助将不胜感激!我知道它与 imagecopyresampled 有关,但我无法弄清楚从图像中心进行裁剪的数学运算。我希望这是我自己的功能,所以请不要推荐我使用其他人的课程。

【问题讨论】:

  • 不要使用 _FILES 数组中的 ['type'] 数据。它是用户提供的,可以很容易地伪造。此外,不要假设上传的图像没有损坏。您没有检查 imagecreatefrom...() 函数实际上是否成功。同样,您的文件名受制于竞争条件 - 如果创建缩略图的时间超过 1 秒,则全尺寸图像将具有不同的文件名。也许没关系,但值得指出。

标签: php image crop


【解决方案1】:

$full_tmp = imagecreatetruecolor($full_width, $full_height); 之后,添加...

if ($thumb_width > $thumb_height) {
    $thumb_offset = array('x' => ($thumb_width/2 - 25), 'y' => 0);
} else {
    $thumb_offset = array('x' => 0, 'y' => ($thumb_height/2 - 25));
}

$square_tmp = imagecreatetruecolor($thumb_width, $thumb_height);

imagecopyresampled($square_tmp, $src, 0, 0, $thumb_offset['x'], $thumb_offset['y'], 50, 50, $width, $height);

然后像其他两张图片一样保存并销毁临时文件。

【讨论】:

    【解决方案2】:

    看看应该传递给imagecopyresampled的参数,根据PHP手册:

    imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
    

    从第三个参数开始,您基本上定义了源图像上的矩形如何映射到目标图像上的矩形。

    所以你要做的第一件事是计算矩形(xywidthheight),它定义了原始图像的可见区域。这些将分别是函数的第 5、第 6、第 9 和第 10 个参数。

    对于目标矩形,使用0,0 表示x,y,使用$thumb_width,$thumb_height 表示w,h,就像您当前所做的那样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-03
      • 1970-01-01
      • 2011-11-16
      • 1970-01-01
      • 2010-11-03
      • 2010-12-11
      • 2017-05-22
      • 2012-12-27
      相关资源
      最近更新 更多