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 相关文章推荐
jQueryUI如何自定义组件实现代码
Nov 14 Javascript
利用JS自动打开页面上链接的实现代码
Sep 25 Javascript
javascript模拟实现C# String.format函数功能代码
Nov 25 Javascript
JS文本获得焦点清除文本文字的示例代码
Jan 13 Javascript
JavaScript验证18位身份证号码最后一位正确性的实现代码
Aug 07 Javascript
js计算德州扑克牌面值的方法
Mar 04 Javascript
js实现的Easy Tabs选项卡用法实例
Sep 06 Javascript
如何提高Dom访问速度
Jan 05 Javascript
详解js静态检查工具eslint配置文件
Nov 23 Javascript
javascript异步编程的六种方式总结
May 17 Javascript
vue+elementUI中表格高亮或字体颜色改变操作
Nov 02 Javascript
JavaScript实现H5接金币功能(实例代码)
Feb 22 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中filter函数验证、过滤用户输入的数据
2014/01/13 PHP
PHP异常Parse error: syntax error, unexpected T_VAR错误解决方法
2014/05/06 PHP
php判断类是否存在函数class_exists用法分析
2014/11/14 PHP
网页里控制图片大小的相关代码
2006/06/25 Javascript
JavaScript在IE和Firefox浏览器下的7个差异兼容写法小结
2010/06/18 Javascript
javascript循环变量注册dom事件 之强大的闭包
2010/09/08 Javascript
获取div编辑框,textarea,input text的光标位置 兼容IE,FF和Chrome的方法介绍
2012/11/08 Javascript
多个表单中如何获得这个文件上传的网址实现js代码
2013/03/25 Javascript
JS 打印功能代码可实现打印预览、打印设置等
2014/10/31 Javascript
浅析JavaScript 箭头函数 generator Date JSON
2016/05/23 Javascript
AngularJS入门教程之REST和定制服务详解
2016/08/19 Javascript
yarn与npm的命令行小结
2016/10/20 Javascript
JavaScript的兼容性与调试技巧
2016/11/22 Javascript
javascript事件的绑定基础实例讲解(34)
2017/02/14 Javascript
Vue基于NUXT的SSR详解
2017/10/24 Javascript
JavaScript学习总结(一) ECMAScript、BOM、DOM(核心、浏览器对象模型与文档对象模型)
2018/01/07 Javascript
vue 中this.$set 动态绑定数据的案例讲解
2021/01/29 Vue.js
Python常用模块介绍
2014/11/21 Python
举例讲解Python中装饰器的用法
2015/04/27 Python
python 类详解及简单实例
2017/03/24 Python
python中使用xlrd读excel使用xlwt写excel的实例代码
2018/01/31 Python
对Python3 解析html的几种操作方式小结
2019/02/16 Python
CSS3实现swap交换动画
2016/01/19 HTML / CSS
澳大利亚网上玩具商店:Mr Toys Toyworld
2018/03/25 全球购物
ONLY瑞典官网:世界知名服装品牌
2018/06/19 全球购物
韩国演唱会订票网站:StubHub韩国
2019/01/17 全球购物
Desigual美国官方网站:西班牙服装品牌
2019/03/29 全球购物
Expedia西班牙:预订酒店、机票、旅行和廉价度假套餐
2019/04/10 全球购物
英国最大的汽车配件在线商店:Euro Car Parts
2019/09/30 全球购物
常用UNIX 命令(Linux的常用命令)
2015/12/26 面试题
私人房屋买卖协议书
2014/10/04 职场文书
公司承诺书格式范文
2015/04/28 职场文书
管理失职检讨书范文
2015/05/05 职场文书
跑出一片天观后感
2015/06/08 职场文书
2021年最新用于图像处理的Python库总结
2021/06/15 Python
python套接字socket通信
2022/04/01 Python