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;
}
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;
}
}
}
if (!empty($mediaJson)) {
$updateSql = "UPDATE school_news SET media = ? WHERE id = ?";
$updateStmt = $pdo->prepare($updateSql);
$updateStmt->execute([json_encode($mediaJson), $id]);
}