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

avatar
作者
猴君
阅读量:1

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

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!