jquery 上传头像 裁剪插件

安希武 2周前 7浏览 0评论

jQuery上传和裁剪插件的出现,大大方便了我们的网站和应用程序的头像上传和编辑。下面,我们来一步步介绍jQuery上传头像裁剪插件的实现过程。

第一步:引入jQuery库和以下两个插件

<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript" src="/path/to/jquery.form.js"></script>
<script type="text/javascript" src="/path/to/jquery.jcrop.js"></script>

第二步:布局

<div id="upload-image">
   <div id="preview"></div>
   <form id="uploadForm" enctype="multipart/form-data" method="post" action="/path/to/upload/file">
       <input name="file" type="file" />
       <input type="submit" value="上传" />
   </form>
</div>

第三步:jQuery代码

$(function(){
  $('#uploadForm').ajaxForm({
      //上传成功后的回调函数
      success: function(data){
          var imgUrl = data.url;
          $('#preview').html('

第四步:后台处理上传和裁剪

//上传文件
$file = $_FILES['file'];
$upload_path = '/path/to/upload/';
$upload_path = $upload_path . basename( $file['name'] );
if(move_uploaded_file($file['tmp_name'], $upload_path)) {
    //裁剪图片
    $temp_file = '/path/to/temp-file/';
    $x = $_POST['x'];
    $y = $_POST['y'];
    $w = $_POST['w'];
    $h = $_POST['h'];
    $targ_w = $targ_h = 150;
    $jpeg_quality = 90;
    $img_r = imagecreatefromjpeg($upload_path);
    $dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
    imagecopyresampled($dst_r,$img_r,0,0,$x,$y,$targ_w,$targ_h,$w,$h);
    imagejpeg($dst_r, $temp_file, $jpeg_quality);
    $result = array('status' => 1, 'msg' => 'success', 'url' => $temp_file);
} else {
    $result = array('status' => -1, 'msg' => 'fail', 'url' => '');
}
echo json_encode($result);

以上就是基于jQuery实现的头像上传和裁剪功能的全部过程,希望对你有所帮助,让你的网站和应用程序更加完美。