2011-09-02 104 views
0

我的代码中的所有内容都适用于创建上传图片的缩略图。如何使用GD图像功能裁剪图像

现在我需要做的是裁剪从图像的中心$拇指为方形(50×50)

我的继承人功能到目前为止

$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有关,但我无法弄清楚从图像中心裁剪的数学。我希望这是我自己的功能,所以请不要推荐我使用其他人的课程。

+0

请勿使用_FILES数组中的[['type']'数据。它是用户提供的,可以轻松伪造。另外,不要认为上传的图像没有损坏。你不检查'imagecreatefrom ...()'函数实际上是否成功。同样,文件名也会受到竞争条件的影响 - 如果缩略图创建时间大于1秒,全尺寸图像将具有不同的文件名。也许这并不重要,但值得指出。 –

回答

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

然后保存和销毁临时像其他两个图像。

+0

真棒:)非常感谢 – scarhand

0

看看应该传递到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) 

从第三参数,你基本上定义如何对源图像映射到一个矩形的矩形在目标图像上。

所以,你必须做的第一件事是计算定义原始图像的可视区域内的rectanle(xywidthheight)。这些将分别是该函数的第5,6,9和10个参数。

对于目标矩形,使用0,0x,y,并且$thumb_width,$thumb_heightw,h,就像你正在做的事情。