1. 程式人生 > >上傳圖片時壓縮圖片 - 後端做法

上傳圖片時壓縮圖片 - 後端做法

rep create 路徑 creat 彩色 images rom sim 不同

    /**
     * 函數:調整圖片尺寸或生成縮略圖 v 1.1
     * @param $Image 需要調整的圖片(含路徑)
     * @param $Dw 調整時最大寬度;縮略圖時的絕對寬度
     * @param $Dh 調整時最大高度;縮略圖時的絕對高度
     * @param $Type 1,調整尺寸; 2,生成縮略圖
     * @return bool
     */
    public function compressImg($image, $Dw, $Dh, $type)
    {
        if (!file_exists($image
)) { return false; } // 如果需要生成縮略圖,則將原圖拷貝一下重新給$Image賦值(生成縮略圖操作) // 當Type==1的時候,將不拷貝原圖像文件,而是在原來的圖像文件上重新生成縮小後的圖像(調整尺寸操作) if ($type != 1) { copy($image, str_replace(".", "_x.", $image)); $image = str_replace(".", "_x.", $image); }
// 取得文件的類型,根據不同的類型建立不同的對象 $ImgInfo = getimagesize($image); switch ($ImgInfo[2]) { case 1: $Img = @imagecreatefromgif($image); break; case 2: $Img = @imagecreatefromjpeg($image); Break; case
3: $Img = @imagecreatefrompng($image); break; } // 如果對象沒有創建成功,則說明非圖片文件 if (empty($Img)) { // 如果是生成縮略圖的時候出錯,則需要刪掉已經復制的文件 if ($type != 1) { unlink($image); } return false; } // 如果是執行調整尺寸操作則 if ($type == 1) { $w = imagesx($Img); $h = imagesy($Img); $width = $w; $height = $h; if ($width > $Dw) { $Par = $Dw / $width; $width = $Dw; $height = $height * $Par; if ($height > $Dh) { $Par = $Dh / $height; $height = $Dh; $width = $width * $Par; } } elseif ($height > $Dh) { $Par = $Dh / $height; $height = $Dh; $width = $width * $Par; if ($width > $Dw) { $Par = $Dw / $width; $width = $Dw; $height = $height * $Par; } } else { $width = $Dw; $height = $Dh; } $nImg = imagecreatetruecolor($Dw, $Dh); // 新建一個真彩色畫布 $white = imagecolorallocate($nImg, 255, 255, 255); // 填充白底色 imagefill($nImg, 0, 0, $white); if ($h / $w > $Dh / $Dw) { // 高比較大 $width = $w * ($Dh / $h); $IntNW = $Dw - $width; $Dx = $IntNW / 2; $Dy = 0; } else { // 寬比較大 $height = $h * ($Dw / $w); $IntNH = $Dh - $height; $Dx = 0; $Dy = $IntNH / 2; } imagecopyresampled($nImg, $Img, $Dx, $Dy, 0, 0, $width, $height, $w, $h); // 重采樣拷貝部分圖像並調整大小 imagejpeg($nImg, $image); // 以JPEG格式將圖像輸出到瀏覽器或文件 return true; } else { // 如果是執行生成縮略圖操作則 $w = imagesx($Img); $h = imagesy($Img); $nImg = imagecreatetruecolor($Dw, $Dh); $white = imagecolorallocate($nImg, 255, 255, 255); // 填充白底色 imagefill($nImg, 0, 0, $white); if ($h / $w > $Dh / $Dw) { // 高比較大 $width = $w * ($Dh / $h); $IntNW = $Dw - $width; imagecopyresampled($nImg, $Img, $IntNW / 2, 0, 0, 0, $width, $Dh, $w, $h); } else { // 寬比較大 $height = $h * ($Dw / $w); $IntNH = $Dh - $height; imagecopyresampled($nImg, $Img, 0, $IntNH / 2, 0, 0, $Dw, $height, $w, $h); } imagejpeg($nImg, $image); return true; } }

需要註意的是: 如果是要生成寬高相等的圖片,輸出到頁面的時候也要設置寬高等比例的

上傳圖片時壓縮圖片 - 後端做法