如何使用PHP中的imagecrop()函数将图像裁剪到给定的矩形区域?


imagecrop()是PHP中内置的一个函数,用于将图像裁剪到给定的矩形区域。它从给定的矩形区域裁剪图像并返回输出图像。原始图像不会被修改。

语法

resource imagecrop ($image, $rect)

参数

imagecrop()接受两个参数,$image$rect

  • $image − 这是由图像创建函数(例如imagecreatetruecolor())返回的参数。它用于创建图像的大小。

  • $rect − 裁剪矩形是一个数组,包含键X、Y、宽度和高度。

返回值

imagecrop()函数成功时返回裁剪后的图像资源,失败时返回false。

示例

<?php
   // It will create an image from the given image
   $img = imagecreatefrompng('C:\xampp\htdocs\Images\img34.png');
   
   // This will find the size of the image
   $size = min(imagesx($img), imagesy($img));
   
   //This will set the size of the cropped image.
   $img2 = imagecrop($img, ['x' => 0, 'y' => 0, 'width' => 500, 'height' => 320]);
   if($img2 !== FALSE) {
      imagepng($img2, 'C:\xampp\htdocs\pic_cropped.png');
      imagedestroy($img2);
   }
   imagedestroy($img);
?>

输出

使用imagecrop()函数之前的输入图像

使用imagecrop()函数之后的输出图像

示例2

<?php
   //load an image from the local drive folder.
   $filename = 'C:\xampp\htdocs\Images\img34.png';
   $img = imagecreatefrompng($filename );

   $ini_x_size = getimagesize($filename)[0];
   $ini_y_size = getimagesize($filename )[1];

   //the minimum of xlength and ylength to crop.
   $crop_measure = min($ini_x_size, $ini_y_size);
   // Set the content-type header
   //header('Content-Type: image/png');
   $crop_array = array('x' =>0 , 'y' => 0, 'width' => $crop_measure, 'height'=>
   $crop_measure);
   $thumb_img = imagecrop($img, $crop_array);
   imagejpeg($thumb_img, 'thumb.png', 100);
?>

输出

更新于:2021年8月9日

3K+ 浏览量

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.