首先使用一个ini文件来设置要缩放的大小,其中为宽或高0的则为图片放大或缩小,都为0则还是原大小,都不为0都拉抻成指定的大小。
注意:ini文件使用php解释时为注释文件,什么也没有输出,这是为了安全起见而故意为之。而;则是ini文件的注释。
我设置的ini文件例子如下:
<BR><?php <BR>/* <BR>;Translate the image format using the original image size <BR>[Translation] <BR>width=0 <BR>height=0 <br><br>;Stretch the image to the specified size <BR>[Stretch] <BR>width=800 <BR>height=600 <br><br>;Zoom the image to the specified Width with height auto size <BR>[AutoHeight] <BR>width=740 <BR>height=0 <br><br>;Zoom the image to the specified Height with width auto size <BR>[AutoWidth] <BR>width=0 <BR>height=380 <BR>*/ <BR>?> <BR>
下面是编写的缩放图片的php代码,其中变量classes是一个数组,可以选择任意多个ini文件中指定的设置:
<BR><?php <BR>$oimg = "test.jpg";//Original image name <BR>$classes = array('Translation','AutoHeight','AutoWidth','Stretch');//Give classes for the new creating images' size which are defined in the specified ini file <BR>$suffix = 'jpg';//The new image's suffix <BR>$inifile = 'image.ini.php'; <br><br>$size = getimagesize($oimg); <BR>$x = $size[0]/$size[1]; <BR>$name = explode('.',$oimg); <br><br>if(!file_exists($inifile)) die('Ini file does not exist!'); <BR>$cn = parse_ini_file($ini<strong style="color:transparent">来2源gaodaima#com搞(代@码&网</strong><label>搞gaodaima代码</label>file,true);//Parse the class style image size from ini file <BR>foreach($classes as $class){ <BR>foreach($cn as $k=>$v){ <BR>if($k==$class){ <BR>if($v['width'] && $v['height']){ <BR>$thumbWidth = $v['width']; <BR>$thumbHeight = $v['height']; <BR>}elseif($v['width']){ <BR>$thumbWidth = $v['width']; <BR>$thumbHeight = round($thumbWidth/$x); <BR>}elseif($v['height']){ <BR>$thumbHeight = $v['height']; <BR>$thumbWidth = round($thumbHeight*$x); <BR>}else{ <BR>$thumbWidth = $size[0]; <BR>$thumbHeight = $size[1]; <BR>} <BR>break; <BR>} <BR>} <BR>if(!isset($thumbHeight) && !isset($thumbWidth)) die('Ini file Settings error!'); <br><br>$nimg = $name[0].'_'.$class.'.'.$suffix;//New image file name <BR>$source = imagecreatefromjpeg($oimg); <BR>$thumb = imagecreatetruecolor($thumbWidth, $thumbHeight); <BR>imagecopyresampled($thumb,$source,0,0,0,0,$thumbWidth,$thumbHeight,$size[0],$size[1]); <br><br>if($suffix=='jpg') $method = 'imagejpeg'; <BR>else $method='image'.$suffix; <BR>$method($thumb, $nimg); <BR>imagedestroy($thumb);//Release the image source <BR>imagedestroy($source); <BR>} <BR>?> <BR>