/* 检查原始文件是否存在及获得原始文件的信息 */ $org_info = @getimagesize($img); $img_org = $this->img_resource($img, $org_info[2]); /* 原始图片以及缩略图的尺寸比例 */ $scale_org = $org_info[0] / $org_info[1]; /* 处理只有缩略图宽和高有一个为0的情况,这时背景和缩略图一样大 */ if ($thumb_width == 0 && $thumb_height == 0) { $thumb_width = $org_info[0]; $thumb_height = $org_info[1]; } else { if ($thumb_width == 0) { $thumb_width = $thumb_height * $scale_org; } if ($thumb_height == 0) { $thumb_height = $thumb_width / $scale_org; } } /* 创建缩略图的标志符 */ if ($gd == 2) { $img_thumb = imagecreatetruecolor($thumb_width, $thumb_height); } else { $img_thumb = imagecreate($thumb_width, $thumb_height); } $clr = imagecolorallocate($img_thumb, 255, 255, 255); imagefilledrectangle($img_thumb, 0, 0, $thumb_width, $thumb_height, $clr); if ($org_info[0] / $thumb_width > $org_info[1] / $thumb_height) { $lessen_width = $thumb_width; $lessen_height = $thumb_width / $scale_org; } else { /* 原始图片比较高,则以高度为准 */ $lessen_width = $thumb_height * $scale_org; $lessen_height = $thumb_height; } $dst_x = ($thumb_width - $lessen_width) / 2; $dst_y = ($thumb_height - $lessen_height) / 2; /* 将原始图片进行缩放处理 */ if ($gd == 2) { imagecopyresampled($img_thumb, $img_org, $dst_x, $dst_y, 0, 0, $lessen_width, $lessen_height, $org_info[0], $org_info[1]); } else { imagecopyresized($img_thumb, $img_org, $dst_x, $dst_y, 0, 0, $lessen_width, $lessen_height, $org_info[0], $org_info[1]); }
复制代码
第二种就是那种不想出现白边,直接从原图上切下来指定的宽高进行使用。这种方式可以分为方位模式和定点模式,方位模式可根据顶端、中端、底端的左中右方位分为9个点作为切割的起点,而定点模式由用户定义切割的起点。此种方式也是先创建指定大小的白图作为画幕,(bbs.it-home.org)再利用函数imagecopy在原图上切割出指定大小以及位置的图片,再次用imagecopyresampled函数将切割下来的图片盖到画幕上。
优点:基本能保证图片不会出现白色底图区域,整个图片空间能被原图的内容充满;缺点:致命的缺点,缩略图不能完全反应出原图的内容,例如有些人物图像,若按照顶部左侧作为切割起点的话,就会可能出现只有半边脸的情况。所以,选择2种模式时,需要根据自己的实际需求来进行。
核心代码:
$img_org = $this->img_resource($img, $org_info[2]); /* 缩略图的尺寸比例 */ $scale_org = $thumb_width / $thumb_height; /* 创建缩略图的标志符 */ if ($gd == 2) { $img_thumb = imagecreatetruecolor($thumb_width, $thumb_height); } else { $img_thumb = imagecreate($thumb_width, $thumb_height); } $clr = imagecolorallocate($img_thumb, 255, 255, 255); imagefilledrectangle($img_thumb, 0, 0, $thumb_width, $thumb_height, $clr); /* 计算剪切图片的宽度和高度 */ $mid_width = ($org_info[0] $mid_height = ($org_info[1] // 为剪切图像创建背景画板 $mid_img = imagecreatetruecolor($mid_width, $mid_height); //拷贝剪切的图像数据到画板,生成剪切图像 imagecopy($mid_img, $img_org, 0, 0, 0, 0, $mid_width, $mid_height); /* 将原始图片进行缩放处理 */ if ($gd == 2) { imagecopyresampled($img_thumb, $mid_img, 0, 0, 0, 0, $thumb_width, $thumb_height, $mid_width, $mid_height); } else { imagecopyresized($img_thumb, $mid_img, 0, 0, 0, 0, $thumb_width, $thumb_height, $mid_width, $mid_height); }
复制代码