php怎么實(shí)現(xiàn)圖片縮放和裁剪

PHP
小億
83
2024-05-24 18:02:13
欄目: 編程語言

在PHP中實(shí)現(xiàn)圖片縮放和裁剪可以使用GD庫來實(shí)現(xiàn)。下面是一個(gè)簡單的示例代碼:

// 圖片縮放
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);
}

// 調(diào)用示例
$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()函數(shù)用于對(duì)圖片進(jìn)行縮放,cropImage()函數(shù)用于對(duì)圖片進(jìn)行裁剪。你可以根據(jù)需要調(diào)整函數(shù)中的參數(shù)來實(shí)現(xiàn)不同的效果。

0