企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 图片缩略实现 ## 指定长宽缩略 指定长、宽实现图片的缩略效果,缩略图尺寸模仿京东图片的尺寸。 ``` <?php $filename = './images/jd.jpg'; $file_info = getimagesize($filename); if ($file_info) { list($width, $height) = $file_info; } else { die("文件不是真实图片"); } $src_image = imagecreatefromjpeg($filename); $dst_image_50 = imagecreatetruecolor(50, 50); $dst_image_270 = imagecreatetruecolor(270, 270); imagecopyresampled($dst_image_50, $src_image, 0, 0, 0, 0, 50, 50, $width, $height); imagecopyresampled($dst_image_270,$src_image,0,0,0,0,270,270,$width,$height); imagejpeg($dst_image_50,'./images/jd_50x50.jpg'); imagejpeg($dst_image_270,'./images/jd_270x270.jpg'); imagedestroy($dst_image_50); imagedestroy($dst_image_270); imagedestroy($src_image); ``` ## 等比例缩放 指定缩放比例,最大宽度和高度,等比例缩放,可以对缩略图文件添加前缀,选择是否删除缩略图源文件 ``` <?php /** * @param string $file_name 文件名 * @param string $dst_path 缩略图保存路径 * @param string $prefix 缩略图保存的前缀 * @param null $dst_w 目标的最大宽度 * @param null $dst_h 目标的最大高度 * @param float $scale 缩放比例 * @param bool $delete_source 是否删除源文件的标志 */ function thumb($file_name, $dst_path = 'thumb', $prefix = 'thumb_', $dst_w = null, $dst_h = null, $scale = 0.5, $delete_source = false) { $file_info = getImageInfo($file_name); $src_w = $file_info['width']; $src_h = $file_info['height']; // 如果指定最大宽度和高度按照等比例缩放进行处理 if (is_numeric($dst_w) && is_numeric($dst_h)) { $ratio_orig = $src_w / $src_h; if ($dst_w / $dst_h > $ratio_orig) { $dst_w = $dst_h * $ratio_orig; } else { $dst_h = $dst_w / $ratio_orig; } } else { $dst_w = ceil($src_w * $scale); $dst_h = ceil($src_h * $scale); } $dst_image = imagecreatetruecolor($dst_w, $dst_h); $src_image = $file_info['create_fun']($file_name); imagecopyresampled($dst_image, $src_image, 0, 0, 0, 0, $dst_w, $dst_h, $src_w, $src_h); // 检测目标目录是否存在 if ($dst_path && !file_exists($dst_path)) { mkdir($dst_path, 0777, true); } $dst_name = "{$prefix}{$file_info['file_name']}" . $file_info['extension']; $destination = $dst_path ? $dst_path . '/' . $dst_name : $dst_name; // 保存的文件名 $file_info['out_fun']($dst_image, $destination); if ($delete_source) { @unlink($file_name); } imagedestroy($src_image); imagedestroy($dst_image); } /** * @param $filename string 文件名 * @return array */ function getImageInfo($filename) { if (!$info = getimagesize($filename)) { exit('文件不是真实图片!'); } $file_info['file_name'] = pathinfo($filename)['filename']; $file_info['width'] = $info[0]; $file_info['height'] = $info[1]; $mime = image_type_to_mime_type($info[2]); $file_info['extension'] = image_type_to_extension($info[2], true); $file_info['create_fun'] = str_replace('/', 'createfrom', $mime); $file_info['out_fun'] = str_replace('/', '', $mime); return $file_info; } ```