一、按照指定大小缩放图片
/** * Function: 按照指定大小缩放图片 * @param string $file 文件地址 * @param int $imgWidth 新图片宽 * @param int $imgHeight 新图片高 * @param string $fileName 保存文件名 * @throws Exception * Author: yvhsse * Date: 2019-09-19 17:18 */ function resizeAppointImage($file, $imgWidth, $imgHeight,$fileName) { //1.获取图片信息 $info = getimagesize($file); //2.通过编号获取图像类型 $type = image_type_to_extension($info[2], false); //3.在内存中创建和图像类型一样的图像 try { $fun = "imagecreatefrom" . $type; $image = $fun($file); } catch (\Exception $e) { throw new Exception('非法图像文件'); } $target_image = imagecreatetruecolor($imgWidth, $imgHeight); //创建一个彩色的底图 imagecopyresampled($target_image, $image, 0, 0, 0, 0, $imgWidth, $imgHeight, imagesx($image), imagesy($image)); //可以根据类型存放原类型图片 $fileName = $fileName.'.png'; imagepng($target_image, $fileName); //销毁图片 imagedestroy($image); } resizeAppointImage('./avatar.png',100,100,'./ss');
2.按照图片比例缩放图片
/** * Function: 根据图片比例缩放图片 * @param string $file 文件地址 * @param int $maxWidth 图片最大宽度 * @param int $maxHeight 图片最大高度 * @param string $fileName 保存文件名 * @throws Exception * Author: yvhsse * Date: 2019-09-19 17:23 */ function resizeRatioImage($file, $maxWidth, $maxHeight,$fileName) { //1.获取图片信息 $info = getimagesize($file); //2.通过编号获取图像类型 $type = image_type_to_extension($info[2], false); //3.在内存中创建和图像类型一样的图像 try { $fun = "imagecreatefrom" . $type; $image = $fun($file); } catch (\Exception $e) { throw new Exception('非法图像文件'); } $picWidth = imagesx($image); $picHeight = imagesy($image); $source_ratio = $picHeight / $picWidth;//原图比例 $target_ratio = $maxHeight / $maxWidth;//新图比例 if ($source_ratio > $target_ratio) { // 源图过高 $cropped_width = $picWidth; $cropped_height = $picWidth * $target_ratio; $source_x = 0; $source_y = ($picHeight - $cropped_height) / 2; } elseif ($source_ratio < $target_ratio) { // 源图过宽 $cropped_width = $picHeight / $target_ratio; $cropped_height = $picHeight; $source_x = ($picWidth - $cropped_width) / 2; $source_y = 0; } else { //源图适中 $cropped_width = $picWidth; $cropped_height = $picHeight; $source_x = 0; $source_y = 0; } $target_image = imagecreatetruecolor($maxWidth, $maxHeight); $cropped_image = imagecreatetruecolor($cropped_width, $cropped_height); // 裁剪 imagecopy($cropped_image, $image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height); // 缩放 imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $maxWidth, $maxHeight, $cropped_width, $cropped_height); //可以根据类型存放原类型图片 $fileName = $fileName.'.png'; imagepng($target_image, $fileName); //销毁图片 imagedestroy($image); } resizeRatioImage('./avatar.png',100,100,'./ss');