php教程--案例23(生成缩略图)

<?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);

}
?>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虾米大王

有你的支持,我会更有动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值