Home >Backend Development >PHP Tutorial >Sample reference for scaling images in PHP
This article introduces a PHP code that implements a blooming image in equal proportions when making an avatar function. Friends in need can refer to it.
The following is a piece of code I wrote when I was doing an avatar processing program. Achievement: Upload an image, save it as a large avatar, and then shrink it and save it as a small avatar. The specific code is as follows: <?php /** * 等比例绽放图片大小 * edit by bbs.it-home.org */ public function drawImg($from,$w=100,$h=100,$newfile){ $info = getimagesize($from); switch ($info[2]){ case 1: $im = imagecreatefromgif($from); break; case 2: $im = imagecreatefromjpeg($from); break; case 3: $im = imagecreatefrompng($from); break; default: exit('不支持的图像格式'); break; } $temp = pathinfo($from); $name = $temp["basename"];//文件名 $dir = $temp["dirname"];//文件所在的文件夹 $extension = $temp["extension"];//文件扩展名 $width = $info[0];//获取图片宽度 $height = $info[1];//获取图片高度 $per1 = round($width/$height,2);//计算原图长宽比 $per2 = round($w/$h,2);//计算缩略图长宽比 //计算缩放比例 if($per1>$per2||$per1==$per2) { //原图长宽比大于或者等于缩略图长宽比,则按照宽度优先 $per=$w/$width; } if($per1<$per2) { //原图长宽比小于缩略图长宽比,则按照高度优先 $per=$h/$height; } $temp_w = intval($width*$per);//计算原图缩放后的宽度 $temp_h = intval($height*$per);//计算原图缩放后的高度 $dst_im = imagecreatetruecolor($temp_w, $temp_h); //调整大小 imagecopyresized($dst_im, $im, 0, 0, 0, 0, $temp_w, $temp_h, $width, $height); //输出缩小后的图像 //exit($newfile); imagejpeg($dst_im,$dir.'/'.$newfile); imagedestroy($dst_im); imagedestroy($im); } ?> Note: The imagejpeg() function, without adding the save path at the front, has been unsuccessful! After testing, I realized that I need to add a save path! |