썸네일 생성
1 업로드된 아바타의 너비와 높이를 가져옵니다
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/2/28 0028 * Time: 下午 1:18 */ header('Content-type:text/html;charset=utf-8'); $info=array('id'=>1,'name'=>'张三'); //接收并处理上传图像 if(!empty($_FILES['pic'])){ $pic_info=$_FILES['pic']; //获取图片大小 $image_info=getimagesize($pic_info['tmp_name']); echo '<pre>'; print_r($image_info); echo '</pre>'; $width=$image_info[0]; $height=$image_info[1]; } ?> <form action="" method="post" enctype="multipart/form-data"> <h2>编辑用户头像</h2> <p>用户姓名:<?php echo $info['name'];?></p> <p>现有头像:</p><img src="<?php echo './'.$info['id'].'.jpg?rand='.rand() ;?>" onerror="this.src='./default.jpg'" /><br> 上传头像:<input name="pic" type="file"><br> <input type="submit" value="保存头像"> </form>
작업은 다음과 같습니다.
2. 썸네일의 최대 너비와 높이를 계산합니다. <?php
//设置最大宽度和高度
$maxwidth=$maxheight=90;
//自动计算缩略图的宽和高
if($width>$height){
//第一种方式
$newwidth=$maxwidth;
$newheight=round($newwidth*$height/$width);
}else{
$newheight=$maxheight;
$newwidth=round($newheight*$width/$height);
}
//第二种方式
// $percent=0.2; //定义缩略图的缩放比例
// $newwidth=$width*$percent;
// $newheight=$height*$percent;
<?php
//绘制画布
$thumb=imagecreatetruecolor($newwidth,$newheight);
//依据原图创建一个与原图一样的新的图像
$source=imagecreatefromjpeg($pic_info['tmp_name']);
//依据原图创建缩略图
imagecopyresized($thumb,$source,0,0,0,0,$newwidth,$newheight,$width,$height);
<?php
//设置缩略图保存路径
$new_file='./'.$info['id'].'.jpg';
//保存缩略图到指定目录
// header('Content-type:image/jpeg');
imagejpeg($thumb,$new_file,100);
전체 코드
imagesize.php:
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/2/28 0028 * Time: 下午 1:18 */ header('Content-type:text/html;charset=utf-8'); $info=array('id'=>1,'name'=>'张三'); //接收并处理上传图像 if(!empty($_FILES['pic'])){ $pic_info=$_FILES['pic']; //获取图片大小 $image_info=getimagesize($pic_info['tmp_name']); echo '<pre>'; print_r($image_info); echo '</pre>'; $width=$image_info[0]; $height=$image_info[1]; //设置最大宽度和高度 $maxwidth=$maxheight=90; //自动计算缩略图的宽和高 //第一种方式 if($width>$height){ $newwidth=$maxwidth; $newheight=round($newwidth*$height/$width); }else{ $newheight=$maxheight; $newwidth=round($newheight*$width/$height); } //第二种方式 // $percent=0.2; //定义缩略图的缩放比例 // $newwidth=$width*$percent; // $newheight=$height*$percent; //绘制画布 $thumb=imagecreatetruecolor($newwidth,$newheight); //依据原图创建一个与原图一样的新的图像 $source=imagecreatefromjpeg($pic_info['tmp_name']); //依据原图创建缩略图 imagecopyresized($thumb,$source,0,0,0,0,$newwidth,$newheight,$width,$height); //设置缩略图保存路径 $new_file='./'.$info['id'].'.jpg'; //保存缩略图到指定目录 // header('Content-type:image/jpeg'); imagejpeg($thumb,$new_file,100); } ?> <form action="" method="post" enctype="multipart/form-data"> <h2>编辑用户头像</h2> <p>用户姓名:<?php echo $info['name'];?></p> <p>现有头像:</p><img src="<?php echo './'.$info['id'].'.jpg?rand='.rand() ;?>" onerror="this.src='./default.jpg'" /><br> 上传头像:<input name="pic" type="file"><br> <input type="submit" value="保存头像"> </form>
실행 결과는 다음과 같습니다.