PHP上传图片并生成缩略图_1

来源:互联网 发布:真人录音配音软件 编辑:程序博客网 时间:2024/06/07 10:23

图片上传页面(upload.php):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

    <title>图片上传</title>

</head>

<body>

    <center>

        <!-- 表单中必须设置enctype="multipart/form-data" -->

        <form method="post" action="result.php" enctype="multipart/form-data" onsubmit="if(this.upImg.value==''){alert('请选择要上传的文件!');return false;}">

            <!-- 设置上传文件大小的上限,name必须为MAX_FILE_SIZE,此例限制为200KB -->

            <input type="hidden" name="MAX_FILE_SIZE" value="204800">

            <input name="upImg" type="file" />&nbsp;&nbsp;<input type="submit" value="上传" />

        </form>

    </center>

</body>

</html>

数据处理页面(result.php):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

  <title>上传处理</title>

</head>

<body>

<?php      

    $allow_type=array("jpg","png","gif");//允许上传的图片类型

    $name=$_FILES['upImg']['name']; //客户端文件的原名称

    $upload_dir="upload/";//图片保存目录

     //strtolower 将字符串转为小写

    $file_suffix=strtolower(getFileSuffix($name));

    if(!in_array($file_suffix,$allow_type))

    {

         //implode 把数组元素组合为字符串        

        $all_type=implode("",$allow_type);

        exit("<script>alert('您只能上传 $all_type 格式的图片!');history.back();</script>");

     }   

     //explode 把字符串分割为数组

    $name_array=explode(".",$name);

    do
    {

        $name_array[0]=randomFileName();

        $name=implode(".",$name_array);

        $upload_file=$upload_dir.$name;

    }while(file_exists($upload_file));

    $tmp_name=$_FILES['upImg']['tmp_name'];

     //is_uploaded_file 判断文件是否是通过HTTP POST上传的

    if(is_uploaded_file($tmp_name))

    {      

        /*

         //限制上传文件的大小,此例只保存缩略图就不需要了

        if($_FILES['upImg']['size'] > 204800)

        {

              exit("<script>alert('上传的图片请不要超过200KB');history.back();</script>");

        }

        */

         //move_uploaded_file 将上传文件移至指定目录

        if(move_uploaded_file($tmp_name,$upload_file))

        {

            makeThumbnail($upload_file,$upload_file,120,120);

              echo "<center><h2>图片已成功上传!</h2><img src='$upload_file'></center>";                  

        }

    }