PHP文件(图片)上传

来源:互联网 发布:java中类和对象的用法 编辑:程序博客网 时间:2024/05/16 04:28

提交表单<input type="file" name="image" />,表单设置属性enctype="multipart/form-data"


提交处理页面:

$imgname = strtolower($_FILES['image']['name']);

$type = substr(strrchr($imgname, '.'), 1);

if (!in_array($type, array('jpg', 'jpeg', 'png', 'gif', 'bmp'))) {

     echo('当前图片图片格式不支持,支持jpg、gif、png、bmp格式!');

     exit;

}

 $upload_tmp_file = ROOT . '/data/tmp/article_' . random(6, 0) . '.' . $type;

 $filepath = '/data/attach/article/article' . random(6, 0) . '.' . $type;

 mkdir(ROOT . '/data/attach/article');

 if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_tmp_file)) {

    image_resize($upload_tmp_file, ROOT . $filepath, 260, 180);    //生成缩略图

    echo('上传成功');

 }

//创建目录

function mkdir($path) {

    if (!file_exists($path)) {

        forcemkdir(dirname($path));

        mkdir($path, 0777);

    }

}

//生成缩略图

function image_resize($src, $dst, $width, $height, $crop = 0) {

    if (!list($w, $h) = getimagesize($src))

        return "Unsupported picture type!";


    $type = strtolower(substr(strrchr($src, "."), 1));

    if ($type == 'jpeg')

        $type = 'jpg';

    switch ($type) {

        case 'bmp': $img = imagecreatefromwbmp($src);

            break;

        case 'gif': $img = imagecreatefromgif($src);

            break;

        case 'jpg': $img = imagecreatefromjpeg($src);

            break;

        case 'png': $img = imagecreatefrompng($src);

            break;

        default : return false;

    }

// resize

    if ($crop) {

        if ($w < $width or $h < $height) {

            rename($src, $dst);

            return true;

        }

        $ratio = max($width / $w, $height / $h);

        $h = $height / $ratio;

        $x = ($w - $width / $ratio) / 2;

        $w = $width / $ratio;

    } else {

        if ($w < $width and $h < $height) {

            rename($src, $dst);

            return true;

        }

        $ratio = min($width / $w, $height / $h);

        $width = $w * $ratio;

        $height = $h * $ratio;

        $x = 0;

    }

    $new = imagecreatetruecolor($width, $height);

// preserve transparency

    if ($type == "gif" or $type == "png") {

        imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));

        imagealphablending($new, false);

        imagesavealpha($new, true);

    }


    imagecopyresampled($new, $img, 0, 0, $x, 0, $width, $height, $w, $h);


    switch ($type) {

        case 'bmp': imagewbmp($new, $dst);

            break;

        case 'gif': imagegif($new, $dst);

            break;

        case 'jpg': imagejpeg($new, $dst);

            break;

        case 'png': imagepng($new, $dst);

            break;

    }

    return true;

}

0 0
原创粉丝点击