php以图片中心为基准任意调整图片尺寸并输出显示
浏览量:391
这个类库可以在比例不失真的前提下,让图片按照期望的宽和高来显示,多余的部分自动被裁切掉。当然,如果你能够提供存储路径,该类库可以将生成的图片按该路径保存下来
why:
使用方法:
<html> <body> <?php $url='/images/2019-07.jpg'; $output_width='500'; $output_height='500'; ?> <img src="<?php echo 'getimage.php?url='.$url.'&w='.$output_width.'&h='.$output_height;?>"> </body> </html>
how:
调用:
class Fillcanvasbysize{
public function execute($urls,$output_width=60,$output_height=60,$saveDir=false,$suffix='_thumb'){
if(!file_exists($urls)){return 'erro1';exit;}//图片不存在
$img_info = getimagesize($urls);
list($width, $height)=$img_info;
if(($width/$height)>=($output_width/$output_height)){
$ori_img=array(
'x' => ceil(($width-$height*$output_width/$output_height)/2) ,
'y' => 0,
'w' => ceil($height*$output_width/$output_height) ,
'h' => $height);
$op_img=array(
'x' => 0,
'y' => 0,
'w' => $output_width,
'h' => $output_height);
}else{
$ori_img=array(
'x' => 0,
'y' => ceil(($height-$width*$output_height/$output_width)/2),
'w' => $width,
'h' => ceil($width*$output_height/$output_width));
$op_img=array(
'x' => 0,
'y' => 0,
'w' => $output_width,
'h' => $output_height);
}
$src= NULL;
$ss=$img_info[2];
if($ss==1){
$src=imagecreatefromgif($urls);
}elseif($ss==2){
$src=imagecreatefromjpeg($urls);
}elseif($ss==3){
$src=imagecreatefrompng($urls);
}else{
return 'erro2';exit;//图片格式错误
}
$dst=imagecreatetruecolor($output_width, $output_height);//新建一个真彩色图像
imagecopyresampled($dst, $src, $op_img['x'], $op_img['y'], $ori_img['x'], $ori_img['y'], $op_img['w'], $op_img['h'], $ori_img['w'], $ori_img['h']);//重采样拷贝部分图像并调整大小
if($saveDir!=false){
$filename = end(explode('/' , $urls));
$filename = (explode('.' , $filename,-1));
$filename = implode('.' , $filename);
$saveDir = $_SERVER['DOCUMENT_ROOT']."/".$saveDir."/".$filename.$suffix.".jpeg";
}else{
header('Content-Type: image/jpeg');
$saveDir = null;
}
imagejpeg($dst,$saveDir,100);
imagedestroy($src);
imagedestroy($dst);
return $saveDir;
}
}
if($_GET) extract($_GET, EXTR_SKIP);
if(empty($w) or empty($h) or empty($url)){die;}
if(strpos($url,'www')===false){$url = $_SERVER['DOCUMENT_ROOT'] . $url;}
$image = new Fillcanvasbysize();
$image->execute($url,$w,$h);


感谢支持与鼓励~