簡體   English   中英

如何使用GD圖像功能裁剪圖像

[英]How to crop image using GD image functions

我的代碼中的所有內容都非常適合創建上傳圖片的縮略圖。

現在我要做的就是將圖像中心的$ 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有關,但我無法從圖像中心算出裁剪的數學運算。 我希望這是我自己的功能,所以請不要推薦我使用其他人的課程。

就在$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);

然后像其他兩個圖像一樣保存並銷毀溫度。

查看根據PHP手冊應傳遞給imagecopyresampled的參數:

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,0x,y ,和$thumb_width,$thumb_heightw,h ,就像你正在做的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM