function createimage($srcimageurl, $dirimageurl, $width, $height)
{$img;$srcw;$new_width;$srch;$new_height;// 图片类型$type = substr(strrchr($srcimageurl, .), 1);// 初始化图像 if($type == jpg) $img = imagecreatefromjpeg($srcimageurl); if($type == gif) $img = imagecreatefromgif($srcimageurl); if($type == png) $img = imagecreatefrompng($srcimageurl);$srcw = imagesx($img);
$srch = imagesy($img);if ($srcw / $srch > $width / $height)
{if ($srcw > $width){$new_width = $width;$new_height = $srch * ($width / $srcw);}else{$new_width = $srcw;$new_height = $srch;}}else{if ($srch > $height){$new_height = $height;$new_width = $srcw * ($height / $srch);}else{$new_width = $srcw;$new_height = $srch;}}$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_image, $img, 0, 0, 0, 0, $new_width, $new_height, $srcw, $srch);imagejpeg($new_image, $dirimageurl);imagedestroy($img);
imagedestroy($new_image);}
复制代码
3、改进后代码:
$o_width || $height>$o_height){//原图宽或高比规定的尺寸小,进行压缩
$newwidth=$o_width;
$newheight=$o_height;
if($o_width>$width){
$newwidth=$width;
$newheight=$o_height*$width/$o_width;
}
if($newheight>$height){
$newwidth=$newwidth*$height/$newheight;
$newheight=$height;
}
//缩略图片
$new_img = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($new_img, $temp_img, 0, 0, 0, 0, $newwidth, $newheight, $o_width, $o_height);
imagejpeg($new_img , $d_photo);
imagedestroy($new_img);
}else{//原图宽与高都比规定尺寸大,进行压缩后裁剪
if($o_height*$width/$o_width>$height){//先确定width与规定相同,如果height比规定大,则ok
$newwidth=$width;
$newheight=$o_height*$width/$o_width;
$x=0;
$y=($newheight-$height)/2;
}else{ //否则确定height与规定相同,width自适应
$newwidth=$o_width*$height/$o_height;
$newheight=$height;
$x=($newwidth-$width)/2;
$y=0;
}
//缩略图片
$new_img = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($new_img, $temp_img, 0, 0, 0, 0, $newwidth, $newheight, $o_width, $o_height);
imagejpeg($new_img , $d_photo);
imagedestroy($new_img);
$temp_img = imagecreatefromjpeg($d_photo);
$o_width = imagesx($temp_img); //取得缩略图宽
$o_height = imagesy($temp_img); //取得缩略图高
//裁剪图片
$new_imgx = imagecreatetruecolor($width,$height);
imagecopyresampled($new_imgx,$temp_img,0,0,$x,$y,$width,$height,$width,$height);
imagejpeg($new_imgx , $d_photo);
imagedestroy($new_imgx);
}}?>
复制代码