<?php
//case 23 生成缩略图
$info = array('id'=>234,'name'=>'王五');
?>
<html>
<head>
<title>用户头像上传</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<h2>编辑用户头像</h2>
<p>用户姓名:<?php echo $info['name'];?></p>
<p>现有头像:</p>
<img src="<?php echo './img/'.$info['id'].'.jpg?rand='.rand();?>" onerror="this.src='./img/default.jpg'" border="1"/>
<br>
上传头像:<input name="pic" type="file"><br>
<input type="submit" name="up_load" value="保存头像">
</form>
</body>
</html>
<?php
//
if(isset($_FILES['pic']))
{
$pic_info = $_FILES['pic'];
if($pic_info['error'] > 0)
{
$error_msg = '上传错误:';
switch ($pic_info['error']) {
case 1:
$error_msg .= '文件大小超过了php配置文件中upload_max_filesize选项的限制值';
break;
case 2:
$error_msg .= '文件大小超过了表单中max_file选项的值';
break;
case 3:
$error_msg .= '文件只有部分被上传';
break;
case 4:
$error_msg .= '没有文件被上传';
break;
case 6:
$error_msg .= '找不到临时文件夹';
break;
case 7:
$error_msg .= '文件写入失败!';
break;
default:
$error_msg .= '未知错误';
break;
}
die($error_msg);
}
$type = substr(strrchr($pic_info['name'],'.'),1);
if ($type !== 'jpg')
{
die('图像类型不符合要求,允许的类型为:jpg');
}
//获得图片尺寸
$img_info = getimagesize($pic_info['tmp_name']);
//获得图片宽
$width = $img_info[0];
//获得图片高
$height = $img_info[1];
echo "width=$width,height=$height";
echo "<br>";
$max_width = $max_height = 90;
$new_width = $new_height = 60;
//判断宽大于高
if($width > $height)
{
$new_width = $max_width;
$new_height = round($new_width * $height / $width);
}
else
{
$new_height = $max_height;
$new_width = round($new_height * $width / $height);
}
echo "new_width=$new_width,new_height=$new_height";
//创建画布
$thumb = imagecreatetruecolor($new_width,$new_height);
//源图
$source = imagecreatefromjpeg($pic_info['tmp_name']);
//复制图
imagecopyresized($thumb,$source,0,0,0,0,$new_width,$new_height,$width,$height);
$new1 = './img/'.$info['id'].'.jpg';
//保存图片
imagejpeg($thumb,$new1,100);
}
?>