在PHP中實現圖片縮放和裁剪可以使用GD庫來實現。下面是一個簡單的示例代碼:
// 圖片縮放
function resizeImage($source, $dest, $newWidth, $newHeight) {
$sourceImage = imagecreatefromjpeg($source);
$resizedImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($resizedImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, imagesx($sourceImage), imagesy($sourceImage));
imagejpeg($resizedImage, $dest);
imagedestroy($sourceImage);
imagedestroy($resizedImage);
}
// 圖片裁剪
function cropImage($source, $dest, $newWidth, $newHeight, $x, $y) {
$sourceImage = imagecreatefromjpeg($source);
$croppedImage = imagecrop($sourceImage, ['x' => $x, 'y' => $y, 'width' => $newWidth, 'height' => $newHeight]);
imagejpeg($croppedImage, $dest);
imagedestroy($sourceImage);
imagedestroy($croppedImage);
}
// 調用示例
$sourceImage = 'source.jpg';
$destImage = 'resized.jpg';
$newWidth = 200;
$newHeight = 200;
resizeImage($sourceImage, $destImage, $newWidth, $newHeight);
$sourceImage = 'source.jpg';
$destImage = 'cropped.jpg';
$newWidth = 200;
$newHeight = 200;
$x = 50;
$y = 50;
cropImage($sourceImage, $destImage, $newWidth, $newHeight, $x, $y);
以上代碼中,resizeImage()
函數用于對圖片進行縮放,cropImage()
函數用于對圖片進行裁剪。你可以根據需要調整函數中的參數來實現不同的效果。