jQuery插件jcrop+Fileapi完美实现图片上传+裁剪+预览的代码分享


Posted in Javascript onApril 22, 2015

网页端 裁剪图片,不需要经过服务器。

这个是用 https://github.com/mailru/FileAPI 框架实现的。配合jcrop.

高级浏览器 使用 canvas 裁剪,ie6 7 8使用 flash过度。

核心代码:

var el = $('input').get(0);
     
     seajs.use(['gallery/jcrop/0.9.12/jcrop.css','gallery/jcrop/0.9.12/jcrop.js'] ,function(){
     
    FileAPI.event.on(el, 'change', function (evt){
      var files = FileAPI.getFiles(evt); // Retrieve file list
 
      FileAPI.filterFiles(files, function (file, info){
        if( !/^image/.test(file.type)  ){
          alert('图片格式不正确');
          return false;
        }
        else if(file.size > 20 * FileAPI.MB){
          alert('图片必须小于20M');
           return false;
        }
        else{
          return true;
        }
        
      }, function (files, rejected){
        console.log(files);
         
        if( files.length ){
          var file = files[0];
           var img0 = FileAPI.Image(file);
           var img1 = FileAPI.Image(file);
           var ratio = 0;
          FileAPI.getInfo(file, function (err, info) {  //get image ratio
              if (!err) {
                if (info.width > info.height) {
                  ratio = info.width / 500;
                }
                else {
                  ratio = info.height / 500;
                }
              }
            });
 
            img0.resize(500, 500, 'max')   //place image and register jcrop
                .get(function(err, img) {
                  $('#img2').empty();
                  $('#img2').append($(img));
 
                  $('#img2').children().Jcrop({
                    aspectRatio: 1,
                    bgColor: 'rgba(0,0,0,0.4)',
                    onSelect: function(c) {
                      img1.matrix.sx = c.x * ratio;
                      img1.matrix.sy = c.y * ratio;
                      img1.matrix.sw = c.w * ratio;
                      img1.matrix.sh = c.h * ratio;
                      img1.matrix.dw = 500;
                      img1.matrix.dh = 500;
 
                      img1.get(function(err, img) {
                        // $('#img3').empty();
                        //   $('#img3').append($(img));
                        $('#img3').html($(img));
                      });
 
                    }
                  });
                });
                  $('#btn').on('click',function(){
                        FileAPI.upload({
//                          url: '/testUpFile/upFile',
                          // headers: { 'Content-Type': 'multipart/form-data' },
                          files: { images: img1 },
                          progress: function (evt){ /* ... */ },
                          complete: function (err, xhr){ /* ... */
                            //alert(xhr.responseText);
                            console.log(xhr);
                          }
                        });              
                  });
          }
        });
      });
  });

完整代码:

<!DOCTYPE html>
<html>
  <head>
    <title>TODO supply a title</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
    <script src="./jquery.min.js"></script>  
    <script src="./jcrop/jquery.Jcrop.min.js"></script>
    <link href="./jcrop/jquery.Jcrop.min.css" rel="stylesheet">
  </head>
  <style>
    
    .upload-btn {
  width: 130px;
  height: 25px;
  overflow: hidden;
  position: relative;
  border: 3px solid #06c;
  border-radius: 5px;
  background: #0cf;

}
  .upload-btn:hover {
    background: #09f;
  }
  .upload-btn__txt {
    z-index: 1;
    position: relative;
    color: #fff;
    font-size: 18px;
    font-family: "Helvetica Neue";
    line-height: 24px;
    text-align: center;
    text-shadow: 0 1px 1px #000;
  }
  .upload-btn input {
    top: -10px;
    right: -40px;
    z-index: 2;
    position: absolute;
    cursor: pointer;
    opacity: 0;
    filter: alpha(opacity=0);
    font-size: 50px;
  }
    
  </style>
 
  
  <body>
    <div>
    <!-- "js-fileapi-wrapper" -- required class -->
    <div class="js-fileapi-wrapper upload-btn" id="choose">
       
      <input name="files" type="file" multiple />
      <button id="btn">上传</button>
    </div>
    <div id="images">
 
      <p style="margin-top: 40px;"></p>
      
      <div id="img2" ></div>
      
      <div id="img3"></div>
    </div>

  </div>

  <script>window.FileAPI = { staticPath: './fileapi/' };</script>
  <script src="./fileapi/FileAPI.min.js"></script>
  <script>
 
    var el = $('input').get(0);
    
 
    FileAPI.event.on(el, 'change', function (evt){
      var files = FileAPI.getFiles(evt); // Retrieve file list

      FileAPI.filterFiles(files, function (file, info){
        if( !/^image/.test(file.type)  ){
          alert('图片格式不正确');
          return false;
        }
        else if(file.size > 20 * FileAPI.MB){
          alert('图片必须小于20M');
           return false;
        }
        else{
          return true;
        }
        
      }, function (files, rejected){
 
        
        if( files.length ){
          var file = files[0];
           var img0 = FileAPI.Image(file);
           var img1 = FileAPI.Image(file);
           var ratio = 0;
          FileAPI.getInfo(file, function (err, info) {  //get image ratio
              if (!err) {
                if (info.width > info.height) {
                  ratio = info.width / 500;
                }
                else {
                  ratio = info.height / 500;
                }
              }
            });

            img0.resize(500, 500, 'max')   //place image and register jcrop
                .get(function(err, img) {
                  $('#img2').empty();
                  $('#img2').append($(img));

                  $('#img2').children().Jcrop({
                    aspectRatio: 1,
                    bgColor: 'rgba(0,0,0,0.4)',
                    onSelect: function(c) {
                      img1.matrix.sx = c.x * ratio;
                      img1.matrix.sy = c.y * ratio;
                      img1.matrix.sw = c.w * ratio;
                      img1.matrix.sh = c.h * ratio;
                      img1.matrix.dw = 500;
                      img1.matrix.dh = 500;

                      img1.get(function(err, img) {
                        // $('#img3').empty();
                        //   $('#img3').append($(img));
                        $('#img3').html($(img));
                      });

                    }
                  });
                });
                  $('#btn').on('click',function(){
                        FileAPI.upload({
                        url: '/testUpFile/upFile',
 
                          files: { images: img1 },
                          progress: function (evt){ /* ... */ },
                          complete: function (err, xhr){ /* ... */
                            //alert(xhr.responseText);
 
                          }
                        });
                    
                  });

          }
        });
      });
  
  </script>
  </body>
</html>

以上所述就是本文的全部内容了,希望大家能够喜欢。

Javascript 相关文章推荐
鼠标滑上去后图片放大浮出效果的js代码
May 28 Javascript
网站404页面3秒后跳到首页的实例代码
Aug 16 Javascript
JavaScript设计模式之观察者模式(发布者-订阅者模式)
Sep 24 Javascript
利用jquery实现下拉框的禁用与启用
Dec 07 Javascript
JS变量及其作用域
Mar 29 Javascript
基于JavaScript实现评论框展开和隐藏功能
Aug 25 Javascript
详解jquery插件jquery.viewport.js学习使用方法
Sep 08 jQuery
微信小程序五子棋游戏的悔棋实现方法【附demo源码下载】
Feb 20 Javascript
原生JS forEach()和map()遍历的区别、兼容写法及jQuery $.each、$.map遍历操作
Feb 27 jQuery
微信小程序文章详情页跳转案例详解
Jul 09 Javascript
小程序角标的添加及绑定购物车数量进行实时更新的实现代码
Dec 07 Javascript
微信小程序scroll-view不能左右滑动问题的解决方法
Jul 09 Javascript
javascript解三阶幻方(九宫格)
Apr 22 #Javascript
javascript递归回溯法解八皇后问题
Apr 22 #Javascript
使用C++为node.js写扩展模块
Apr 22 #Javascript
node.js 使用ejs模板引擎时后缀换成.html
Apr 22 #Javascript
JavaScript模拟深蓝vs卡斯帕罗夫的国际象棋对局示例
Apr 22 #Javascript
jscript读写二进制文件的方法
Apr 22 #Javascript
javascript格式化json显示实例分析
Apr 21 #Javascript
You might like
php 删除数组元素
2009/01/16 PHP
需要发散思维学习PHP
2009/06/29 PHP
php中用于检测一个地理IP地址是否可用的代码
2012/02/19 PHP
PHP实现懒加载的方法
2015/03/07 PHP
PHP实现图片压缩
2020/09/09 PHP
短信提示使用 特效
2007/01/19 Javascript
页面回到顶部的三种实现(锚标记,js)
2012/10/01 Javascript
jQuery实现长按按钮触发事件的方法
2015/02/02 Javascript
js中for in语句的用法讲解
2015/04/24 Javascript
javascript关于open.window子页面执行完成后刷新父页面的问题分析
2015/04/27 Javascript
Ajax中解析Json的两种方法对比分析
2015/06/25 Javascript
简单实现异步编程promise模式
2015/07/31 Javascript
基于jQuery实现以手风琴方式展开和折叠导航菜单
2016/01/28 Javascript
jQuery实现返回顶部功能
2016/02/23 Javascript
vue.js+boostrap项目实践(案例详解)
2016/09/21 Javascript
jQuery如何防止Ajax重复提交
2016/10/14 Javascript
Easyui ueditor 整合解决不能编辑的问题(推荐)
2017/06/25 Javascript
vue.js全局API之nextTick全面解析
2017/07/07 Javascript
jQuery实现仿京东防抖动菜单效果示例
2018/07/06 jQuery
vue中引入mxGraph的步骤详解
2019/05/17 Javascript
electron 安装,调试,打包的具体使用
2019/11/06 Javascript
用Python制作在地图上模拟瘟疫扩散的Gif图
2015/03/31 Python
Python使用smtp和pop简单收发邮件完整实例
2018/01/09 Python
Django中数据库的数据关系:一对一,一对多,多对多
2018/10/21 Python
python使用pip安装SciPy、SymPy、matplotlib教程
2019/11/20 Python
python科学计算之narray对象用法
2019/11/25 Python
python实现图像拼接功能
2020/03/23 Python
Python request操作步骤及代码实例
2020/04/13 Python
pyCharm 实现关闭代码检查
2020/06/09 Python
详解python爬取弹幕与数据分析
2020/11/14 Python
canvas版人体时钟的实现示例
2021/01/29 HTML / CSS
ruby如何进行集成操作?Ruby能进行多重继承吗?
2013/10/16 面试题
营销专业应届生求职信
2013/11/26 职场文书
小学优秀辅导员事迹材料
2014/05/11 职场文书
医学专业毕业生推荐信
2014/07/12 职场文书
跟班学习心得体会(共6篇)
2016/01/23 职场文书