imagecopyresized
是 PHP 中一個用于調整圖像大小的函數,它可以將一張圖片按比例或指定大小復制到另一張圖片上
以下是一個使用 imagecopyresized
調整 JPEG 圖像大小的示例:
<?php
// 加載原始圖像和目標圖像
$sourceImage = imagecreatefromjpeg('source.jpg');
$destinationImage = imagecreatetruecolor(300, 200);
// 保持 PNG 和 GIF 圖像的透明度
imagealphablending($destinationImage, false);
imagesavealpha($destinationImage, true);
// 獲取原始圖像和目標圖像的尺寸
$sourceWidth = imagesx($sourceImage);
$sourceHeight = imagesy($sourceImage);
$destinationWidth = 300;
$destinationHeight = 200;
// 計算縮放比例
$scaleX = $destinationWidth / $sourceWidth;
$scaleY = $destinationHeight / $sourceHeight;
$scale = min($scaleX, $scaleY);
// 計算新的尺寸
$newWidth = intval($sourceWidth * $scale);
$newHeight = intval($sourceHeight * $scale);
// 將原始圖像按比例縮放到目標圖像上
imagecopyresized($destinationImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $sourceWidth, $sourceHeight);
// 保存調整大小后的圖像
imagejpeg($destinationImage, 'resized_image.jpg', 80);
// 銷毀圖像資源
imagedestroy($sourceImage);
imagedestroy($destinationImage);
?>
在這個示例中,我們首先加載了名為 source.jpg
的原始 JPEG 圖像,然后創建了一個名為 destinationImage
的新圖像,其尺寸為 300x200 像素。接下來,我們使用 imagecopyresized
函數將原始圖像按比例縮放到目標圖像上,并將結果保存為名為 resized_image.jpg
的新 JPEG 圖像。最后,我們銷毀了所有圖像資源。