php图片压缩居中裁剪

用于业务需求,需要进行图片处理,图片压缩生成缩略图,超过规定尺寸要居中裁剪,现封装一个图片处理方法,直接调用即可:

 /**
    * desription 压缩图片
    * @param sting $imgsrc 图片路径
    * @param string $imgdst 压缩后保存路径
    * @param string $imgWidth 新图片宽度
    * @param string $imgHeight 新图片高度
    * @param string $imgHeight 压缩质量0-100
    */
protected function compressed_image($imgsrc,$imgdst,$imgWidth,$imgHeight,$quality=100){
      list($width,$height,$type)=getimagesize($imgsrc);
      $new_width = $imgWidth; //$pic_config['width'];
      $new_height = $imgHeight; //$pic_config['height'];

      //按照比例最小比例压缩  
      if($width/$height > $new_width/$new_height) {
        //以高为标准
        $new_width = $new_height * ($width / $height);
      }else{
        //以宽度为准
        $new_height = $new_width * ($height / $width);
      }

      switch($type){
        case 1:
          //$giftype=check_gifcartoon($imgsrc);
          //if($giftype){
             header('Content-Type:image/gif');
            $image_wp=imagecreatetruecolor($new_width, $new_height);
            $image = imagecreatefromgif($imgsrc);
            imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            //75代表的是质量、压缩图片容量大小
            imagejpeg($image_wp, $imgdst, $quality);
            imagedestroy($image_wp);
          //}
           
          break;
        case 2:
          header('Content-Type:image/jpeg');
          $image_wp=imagecreatetruecolor($new_width, $new_height);
          $image = imagecreatefromjpeg($imgsrc);
          imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
          imagejpeg($image_wp, $imgdst,$quality);
          imagedestroy($image_wp);
          break;
        case 3:
         header('Content-Type:image/png');
          $image_wp=imagecreatetruecolor($new_width, $new_height);
          $image = imagecreatefrompng($imgsrc);
          imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
          imagejpeg($image_wp, $imgdst,$quality);
          imagedestroy($image_wp);
          break;
      }

        //创建目标图像
        $dst_im = imagecreatetruecolor($imgWidth, $imgHeight);
        $white = imagecolorallocate($dst_im, 255, 255, 255);
        imagefill($dst_im, 0, 0, $white);

        //源图像
        $src_im = @imagecreatefromjpeg($imgdst);

        $height = $width = 0;
        if($new_width > $imgWidth) {
            $width = ($new_width - $imgWidth) / 2;
        }
        if($new_height > $imgHeight) {
            $height = ($new_height-$imgHeight) / 2;
        }
        imagecopy( $dst_im, $src_im, 0, 0, $width, $height, $imgWidth, $imgHeight );
        imagejpeg($dst_im, $imgdst);
        imagedestroy($dst_im);
    }

如有疑问可以联系wechat: gratitude369

你可能感兴趣的:(php图片压缩居中裁剪)