PHP

php怎么实现图片缩放和裁剪

小亿
83
2024-05-24 18:02:13
栏目: 编程语言

在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()函数用于对图片进行裁剪。你可以根据需要调整函数中的参数来实现不同的效果。

0
看了该问题的人还看了