笔者在设计http://www.cityxii.cn的主页过程中,有遇到图片缩放问题。由于页面的图片是从论坛里面抽取,而用户在论坛里面所发图片大小不一,展示出来难免会要变形。
http://www.cityxii.cn的主页使用的是SUPESITE7.0,论坛使用discuz7。笔者在这里先把思路理一理:
首先,PHP支持图片的创建、修改。不过依赖GD库。
其次,如何调用PHP图片缩放函数。这里笔者采用GET方法传递参数给图片缩放的代码文件。
下面笔者先把PHP图片缩放的代码贴出来,然后根据代码解释编写思路。
1: $imgpath=$_GET['img'];
2: if ($_GET['w'] != '' && $_GET['h'] != ''){
3: $initWidth = $_GET['w'];
4: $initHeight = $_GET['h'];
5: }else{
6: $initWidth = 340;
7: $initHeight = 270;
8: }
9: if(strpos($imgpath,'thumb.jpg')){
10: $imgpath = substr($imgpath,0,-10);
11: }
12:
13:
14: $im = @imagecreatefromjpeg($imgpath);
15: $imgSize = GetImageSize($imgpath);
16: $imgWidth = $imgSize[0];
17: $imgHeight = $imgSize[1];
18: $proportion = max($initWidth/$imgWidth,$initHeight/$imgHeight);
19: $newImgWidth = $imgWidth*$proportion;
20: $newImgHeight = $imgHeight*$proportion;
21: $tmpImg = imagecreatetruecolor($newImgWidth,$newImgHeight);
22: imagecopyresized($tmpImg, $im, 0, 0, 0, 0, $newImgWidth, $newImgHeight, $imgWidth, $imgHeight);
23:
24: $thumb = imagecreatetruecolor($initWidth, $initHeight);
25: $diffWidth = $newImgWidth > $initWidth ? $newImgWidth - $initWidth : $initWidth - $newImgWidth;
26: $diffHeight = $newImgHeight > $initHeight ? $newImgHeight - $initHeight : $initHeight - $newImgHeight;
27:
28: $x = $diffWidth/2;
29: //$y = $diffHeight/3;
30: $y = 0;
31:
32: imagecopy($thumb, $tmpImg, 0, 0, $x, $y, $initWidth, $initHeight);
33:
34: header('Content-type:image/jpeg');
35: // Output
36: imagejpeg($thumb);
37: ImageDestroy($thumb);
解释一下以上代码。
1. 获得图片的URL,以及最终高宽。
2. line 9 是抽取UCHOME的相册图片,所需的修改。系统默认抽取相册图片本来就是缩略图,也就是以thumb.jpg结尾的图片,过滤掉。
3. line 14~17 导入并获得图片的宽高,line 18~22 计算缩放比例。依最大缩放比例修改原始图片。
4. line 24 后面就是把第3步缩放的图片,COPY到最终宽高图片。
然后,笔者把调用代码给出,以供参考。
1: <img alt="[Image]" src="/phptoimg.php?w=100&h=98&img=$value['pic']" width="100" height="98" border="0"/>