Cropping image in PHP

前端 未结 6 557
不思量自难忘°
不思量自难忘° 2020-11-30 11:01

I\'d like crop an image in PHP and save the file. I know your supposed to use the GD library but i\'m not sure how. Any ideas?

Thanks

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 12:06

    I just created this function and it works for my needs, creating a centered and cropped thumbnail image. It is streamlined and doesn't require multiple imagecopy calls like shown in webGautam's answer.

    Provide the image path, the final width and height, and optionally the quality of the image. I made this for creating thumbnails, so all images are saved as JPGs, you can edit it to accommodate other image types if you require them. The main point here is the math and method of using imagecopyresampled to produce a thumbnail. Images are saved using the same name, plus the image size.

    function resize_crop_image($image_path, $end_width, $end_height, $quality = '') {
     if ($end_width < 1) $end_width = 100;
     if ($end_height < 1) $end_height = 100;
     if ($quality < 1 || $quality > 100) $quality = 60;
    
     $image = false;
     $dot = strrpos($image_path,'.');
     $file = substr($image_path,0,$dot).'-'.$end_width.'x'.$end_height.'.jpg';
     $ext = substr($image_path,$dot+1);
    
     if ($ext == 'jpg' || $ext == 'jpeg') $image = @imagecreatefromjpeg($image_path);
     elseif($ext == 'gif') $image = @imagecreatefromgif($image_path);
     elseif($ext == 'png') $image = @imagecreatefrompng($image_path);
    
     if ($image) {
      $width = imagesx($image);
      $height = imagesy($image);
      $scale = max($end_width/$width, $end_height/$height);
      $new_width = floor($scale*$width);
      $new_height = floor($scale*$height);
      $x = ($new_width != $end_width ? ($width - $end_width) / 2 : 0);
      $y = ($new_height != $end_height ? ($height - $end_height) / 2 : 0);
      $new_image = @imagecreatetruecolor($new_width, $new_height);
    
      imagecopyresampled($new_image,$image,0,0,$x,$y,$new_width,$new_height,$width - $x,$height - $y);
      imagedestroy($image);
      imagejpeg($new_image,$file,$quality);
      imagedestroy($new_image);
    
      return $file;
     }
     return false;
    }
    

提交回复
热议问题