:::

5-2-3 建立縮圖並產生json資料

  1. 為了避免圖片太大,我們可以在上傳的過程中縮圖一下AI有幫我們設計一個縮圖的函數:
    function resizeImage(string $sourcePath, string $destPath, int $targetWidth): bool
    {
        list($width, $height) = getimagesize($sourcePath);
        $ratio = $targetWidth / $width;
        $targetHeight = intval($height * $ratio);
    
        $sourceImage = imagecreatefromstring(file_get_contents($sourcePath));
        $destImage = imagecreatetruecolor($targetWidth, $targetHeight);
    
        imagecopyresampled($destImage, $sourceImage, 0, 0, 0, 0, $targetWidth, $targetHeight, $width, $height);
    
        $result = imagejpeg($destImage, $destPath, 90);
    
        imagedestroy($sourceImage);
        imagedestroy($destImage);
    
        return $result;
    }

     

  2. store() 中,建立目錄後,判斷若是上傳檔案格式為圖片,那就進行縮圖,我們分別將縮圖寬度改為1024和320。
    $uploadDir = "uploads/{$id}/";
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
    
    $mediaJson = [];
    
    if ($_POST['upload_type'] === 'image' && !empty($_FILES['image_files']['name'])) {
        foreach ($_FILES['image_files']['name'] as $key => $name) {
            $tmpName = $_FILES['image_files']['tmp_name'][$key];
            if ($_FILES['image_files']['error'][$key] === UPLOAD_ERR_OK) {
                $extension = pathinfo($name, PATHINFO_EXTENSION);
                $newName = uniqid() . '.' . $extension;
                $destination = $uploadDir . $newName;
    
                // 移動上傳的文件
                move_uploaded_file($tmpName, $destination);
    
                // 創建主圖(寬度800px)
                $mainImage = $uploadDir . 'main_' . $newName;
                resizeImage($destination, $mainImage, 1024);
    
                // 創建縮略圖(寬度200px)
                $thumbImage = $uploadDir . 'thumb_' . $newName;
                resizeImage($destination, $thumbImage, 320);
    
                // 刪除原始上傳的文件
                unlink($destination);
    
                $mediaJson[$mainImage] = $thumbImage;
            }
        }
    }

     

  3. 最後,順便產生json內容,並且存入到該筆資中,如此,日後我們就可以簡單的掌握該新聞有哪些圖片了
    if (!empty($mediaJson)) {
        $updateSql = "UPDATE school_news SET media = ? WHERE id = ?";
        $updateStmt = $pdo->prepare($updateSql);
        $updateStmt->execute([json_encode($mediaJson), $id]);
    }

     


:::

書籍目錄

展開 | 闔起

快速登入


https%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbdsn%3D2018%26tbsn%3D55

計數器

今天: 3776377637763776
昨天: 2489248924892489
總計: 8025758802575880257588025758802575880257588025758