Home  >  Article  >  Backend Development  >  PHP调整Jcrop截取的上传头像功能

PHP调整Jcrop截取的上传头像功能

WBOY
WBOYOriginal
2016-06-13 12:22:271390browse

PHP整合Jcrop截取的上传头像功能

先来看看简单Demo效果图
这里写图片描述
这里写图片描述

Jcrop介绍

Jcrop是一个jQuery插件,它能为你的WEB应用程序快速简单地提供图片裁剪的功能。
特点:
1、对所有图片均unobtrusively(无侵入的,保持DOM简洁)
2、支持宽高比例锁定
3、支持 minSize / maxSize设置
4、支持改变选区或移 动选区时的回调(Callback)
5、支持用键盘微调选 区
6、通过API创建互 动,比如动画效果
7、支持CSS样式

详细请自行百度jcrop

Demo介绍

这个Demo选择整合了jcrop的截取图片插件,
上传图片还是使用file表单提交,php后台处理截图保存。

模块目录如下:
├─controller (控制器)
├─uppict (上传图片暂存位置)
├─userpic (截图保存位置)
└─views (视图)
这里写图片描述

视图代码croppic.php如下:

/*** 20150520 11:50* 作者:Ro* 修改时间 20150522 13:50* 修改内容 合并上传和截取图片功能*///上传文件类型列表$uptypes=array(    'image/jpg',    'image/jpeg',    'image/png'    );?><html><head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    <link rel="stylesheet" href="css/main.css" type="text/css" />    <link rel="stylesheet" href="css/demos.css" type="text/css" />    <link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />    <link rel="stylesheet" href="css/uppic.css" type="text/css" />    <title>头像上传title>head><body>    <div class="container">        <div class="row">            <div class="span12">                <div class="jc-demo-box">                    <div class="clear_float">                                                 if(isset($_GET['name']))                        {                            echo'                            .$_GET['name'].'"  id="target" class="float"/>                            .$_GET['name'].'"  id="real_img"   style="max-width:90%"/>                            
.$_GET['name'].'" class="jcrop-preview float" alt="Preview" />
'
; } else { echo' PHP调整Jcrop截取的上传头像功能 PHP调整Jcrop截取的上传头像功能
Preview
'
; } ?>
div>
<form action="http:///uppic/controller/croppic.php?mothed=up" enctype="multipart/form-data" method="post" name="upform"> 上传文件: <input name="upfile" type="file"> <input type="submit" value="上传图片" class="btn btn-large btn-inverse"><br> 允许上传的文件类型为:=implode(', ',$uptypes)?> form> if(isset($_GET['name'])) { echo '
$_SERVER['HTTP_HOST'].'/uppic/controller/croppic.php?mothed=crop&name='.$_GET['name'].'" method="post" onsubmit="return checkCoords();"> '; } else { echo ' $_SERVER['HTTP_HOST'].'/uppic/controller/croppic.php?mothed=crop&name=default.jpg" method="post" onsubmit="return checkCoords();"> '; } ?> <input type="hidden" id="x" name="x" /> <input type="hidden" id="y" name="y" /> <input type="hidden" id="w" name="w" /> <input type="hidden" id="h" name="h" /> <input type="submit" value="保存" class="btn btn-large btn-inverse"/> form> div> div> div> div><script src="js/jquery.min.js">script><script src="js/jquery.Jcrop.js">script><script src="js/crop.js">script>body>html>

视图js代码crop.js如下:

/** * 20150518 15:35 * author : Ro * changeDate: 20150519 10:25 * changeContext:修改计算坐标算法 *//***检测是否有选取一个区域**/function checkCoords(){    if (parseInt($('#w').val()))       return true;    alert("请截取一个区域再提交保存!");    return false;};jQuery(function($){    var jcrop_api,        boundx,        boundy,    // Grab some information about the preview pane    $preview = $('#preview-pane'),    $pcnt = $('#preview-pane .preview-container'),    $pimg = $('#preview-pane .preview-container img'),    //这里获取的是装img的div宽高    xsize = $pcnt.width(),    ysize = $pcnt.height();    //这里可以设置jcrop的属性,    //如当改变截取区域时激活onChange: updatePreview动作等    $('#target').Jcrop({      onChange: updatePreview,      onSelect: updatePreview,      aspectRatio: xsize / ysize    },function(){      // 用jcrop的getBounds()方法获取真实尺寸      var bounds = this.getBounds();      boundx = bounds[0];      boundy = bounds[1];      // Store the API in the jcrop_api variable      jcrop_api = this;      // Move the preview into the jcrop container for css positioning      $preview.appendTo(jcrop_api.ui.holder);    });    //更新jcrop预览视图    function updatePreview(c)    {      if (parseInt(c.w) > 0)      {        //下面的比例是div的宽高与截图坐标比        var rx = xsize / c.w;        var ry = ysize / c.h;        //改变预览图的大小和显示位置        $pimg.css({          width: Math.round(rx * boundx) + 'px',          height: Math.round(ry * boundy) + 'px',          marginLeft: '-' + Math.round(rx * c.x) + 'px',          marginTop: '-' + Math.round(ry * c.y) + 'px'        });        var realWidth =  $("#real_img").width();        var realHeight = $("#real_img").height();    //记录位置和宽高        $('#x').val(Math.round( c.x * realWidth / boundx ));        $('#y').val(Math.round( c.y * realHeight / boundy));        $('#w').val(Math.round( c.w * realWidth / boundx ));        $('#h').val(Math.round( c.w * realWidth / boundx ));      }    };});

控制器代码croppic.php如下:

/** * 20150520 11:50 * 作者:Ro * 修改时间 20150522 13:50 * 修改内容 合并上传和截取图片功能 * 修改时间 20150527 15:23 * 修改内容 判断png和jpg而作对应操作 *//******************************************************************************参数说明:$max_file_size  : 上传文件大小限制, 单位BYTE$destination_folder : 上传文件路径使用说明:1. 将PHP.INI文件里面的"extension=php_gd2.dll"一行前面的;号去掉,因为我们要用到GD库;2. 将extension_dir =改为你的php_gd2.dll所在目录;******************************************************************************///上传文件类型列表$uptypes=array(    'image/jpg',    'image/jpeg',    'image/png'    );//上传文件大小限制, 单位BYTE$max_file_size=2000000;     //上传文件路径'../uppict/'$destination_folder="../uppict/"; //请求上传图片操作if ($_SERVER['REQUEST_METHOD'] == 'POST' && 'up'==$_GET['mothed']){    //是否存在文件    if (!is_uploaded_file($_FILES["upfile"]["tmp_name"]))    {       echo "图片不存在!";       exit;   }   $file = $_FILES["upfile"];    //检查文件大小   if($max_file_size < $file["size"])   {    echo "文件太大!";    exit;}    //检查文件类型if(!in_array($file["type"], $uptypes)){    echo "文件类型不符!".$file["type"];    exit;}if(!file_exists($destination_folder)){    mkdir($destination_folder);}    //获取信息$filename=$file["tmp_name"];$image_size = getimagesize($filename);$pinfo=pathinfo($file["name"]);$ftype=$pinfo['extension'];    //可以在这修改上传后图片的名字,这里以time()为命名$destination = $destination_folder.time().".".$ftype;    //检查是否已经存在同名文件if (file_exists($destination) && $overwrite != true){    echo "同名文件已经存在了";    exit;}    //上传图片操作if(!move_uploaded_file ($filename, $destination)){    echo "移动文件出错";    exit;}    //获取信息$pinfo=pathinfo($destination);$fname=$pinfo['basename'];    //重定向浏览器 header('Location: http://'.$_SERVER['HTTP_HOST'].'/uppic/views/croppic.php?name='.$fname);     //确保重定向后,后续代码不会被执行 exit;}//请求截图保存操作else if ($_SERVER['REQUEST_METHOD'] == 'POST' && 'crop'==$_GET['mothed']){    //获取图片名    $name=$_GET['name'];    //高宽    $targ_w = $targ_h = 150;    /**     *范围从 0(最差质量,文件更小)     *到 100(最佳质量,文件最大)。     *默认为 IJG 默认的质量值(大约 75)     */    $jpeg_quality = 90;    //图片暂放地址'../uppict/'    $src = "../uppict/".$_GET['name'];    //分开图片名和图片后缀    $arr_name = explode ( ".", $name );    //判断图片后缀选择新建图片方式    $img_r ='';    if ('png' == $arr_name [1])    {        $img_r = imagecreatefrompng ( $src );    } else    {        $img_r = imagecreatefromjpeg ( $src );    }    $dst_r = ImageCreateTrueColor( $targ_w, $targ_h );    //截取图片    imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],$targ_w,$targ_h,$_POST['w'],$_POST['h']);    //判断图片后缀选择生成图片    //保存位置'../userpic/'// 生成图片    if ('png' == $arr_name [1])    {        imagepng ( $dst_r, '../userpic/' . $name );    } else    {        imagejpeg ( $dst_r, '../userpic/' . $name, $jpeg_quality );    }    //显示保存后的图片    echo '.$name.'" />';    exit;}?>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn