php图片处理时有时需要对图片进行二次处理,比如把图片裁剪到指定范围
案例:
/** * 等比缩放图片处理 * @param $sourceImage 原图片 * @param int $height 裁剪高度 * @param int $width 裁剪宽度 * @param string $dir 新图片目录 * @return bool|string * @throws Exception */ public static function dealImageSize($sourceImage, $height=300, $width=300, $dir = "MapSearch/"){ if(empty($sourceImage)){ throw new Exception('缺少必要参数', 400); } $source_path = $sourceImage; $source_info = getimagesize($source_path); $source_width = $source_info[0]; $source_height = $source_info[1]; $source_mime = $source_info['mime']; $source_ratio = $source_height / $source_width; $target_ratio = $height / $width; // 源图过高 if ($source_ratio > $target_ratio) { $cropped_width = $source_width; $cropped_height = $source_width * $target_ratio; $source_x = 0; $source_y = ($source_height - $cropped_height) / 2; } // 源图过宽 elseif ($source_ratio < $target_ratio) { $cropped_width = $source_height / $target_ratio; $cropped_height = $source_height; $source_x = ($source_width - $cropped_width) / 2; $source_y = 0; } // 源图适中 else { $cropped_width = $source_width; $cropped_height = $source_height; $source_x = 0; $source_y = 0; }
//获取图片类型 并载入一个新的画像 [$source_image,$source_type] = self::switchType($source_mime,$source_path); $target_image = imagecreatetruecolor($width, $height); $cropped_image = imagecreatetruecolor($cropped_width, $cropped_height); $tmpDir = EASYSWOOLE_ROOT . '/runtime/'.$dir; if (!file_exists($tmpDir)) { mkdir($tmpDir, 0777, true);//检查是否有该文件夹,如果没有就创建,并给予最高权限 } // 裁剪 imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height); // 缩放 imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $width, $height, $cropped_width, $cropped_height); $file_name = $tmpDir.rand(0000,9999).".".$source_type; imagepng($target_image,$file_name); imagedestroy($target_image); return $file_name; } /**
* 获取图片类型 * @param $source_mime * @param $source_path * @return array|bool */ public static function switchType($source_mime,$source_path){ switch ($source_mime) { case 'image/gif': $source_image = imagecreatefromgif($source_path); $source_type = "gif"; break; case 'image/jpeg': $source_image = imagecreatefromjpeg($source_path); $source_type = "jpg"; break; case 'image/png': $source_type = "png"; $source_image = imagecreatefrompng($source_path); break; default: return false; break; } return [$source_image,$source_type]; }
以上就是今天的全部内容!