6

Croppie.js之图片裁剪压缩上传

h5图片裁剪, 压缩, 上传, 预览是常见功能, 幸运的是我们有cropp.js这款利器.

1. style

  <link rel="Stylesheet" href="https://cdn.bootcss.com/croppie/2.6.2/croppie.css" />
  <style>
    .actions button, 
    .actions a.btn { 
    background-color: #189094; 
    color: white; 
    padding: 10px 15px; 
    border-radius: 3px; 
    border: 1px solid rgba(255, 255, 255, 0.5); 
    font-size: 16px; 
    cursor: pointer; 
    text-decoration: none; 
    text-shadow: none; 
    } 
    .actions button:focus { 
    outline: 0; 
    } 
      
    .actions .file-btn { 
    position: relative; 
    } 
    .actions .file-btn input[type="file"] { 
    position: absolute; 
    top: 0; 
    left: 0; 
    width: 100%; 
    height: 100%; 
    opacity: 0; 
    } 
      
    .actions { 
    padding: 5px 0; 
    } 
    .actions button { 
    margin-right: 5px; 
    } 
    .actions .crop{display:none} 
  </style>

2.html

  <div class="actions"> 
    <button class="file-btn"> 
      <span>上传</span> 
      <input type="file" id="upload" value="选择图片文件" /> 
    </button> 
    <div class="crop"> 
      <div id="upload-demo"></div> 
      <button class="upload-result">裁剪</button> 
    </div> 
    <div id="result"></div> 
  </div> 

3.JavaScript


  <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>
  <script src="https://cdn.bootcss.com/croppie/2.6.2/croppie.js"></script>


$(function(){ 
 var $uploadCrop; 
  
  function readFile(input) { 
    if (input.files && input.files[0]) { 
    var reader = new FileReader(); 
      
    reader.onload = function (e) { 
     $uploadCrop.croppie('bind', { 
      url: e.target.result 
     }); 
    } 
      
    reader.readAsDataURL(input.files[0]); 
   } 
   else { 
    alert("Sorry - you're browser doesn't support the FileReader API"); 
   } 
  } 
  
  $uploadCrop = $('#upload-demo').croppie({ 
   viewport: { 
    width: 200, 
    height: 200, 
    type: 'circle'
   }, 
   boundary: { 
    width: 300, 
    height: 300 
   },
   showZoomer: false,
  }); 
  
  $('#upload').on('change', function () { 
   $(".crop").show(); 
   readFile(this); 
  }); 
  $('.upload-result').on('click', function (ev) { 
   $uploadCrop.croppie('result', 'canvas').then(function (resp) { 
    popupResult({ 
     src: resp 
    }); 
   }); 
  }); 
    
 function popupResult(result) { 
  var html; 
  if (result.html) { 
   html = result.html; 
  } 
  if (result.src) { 
   html = '<img src="' + result.src + '" />'; 
  } 
  $("#result").html(html); 
 } 
}); 

croppie.js挺好用的图片处理插件, 另外还有较好的插件有待研究
http://foliotek.github.io/Cro...
https://github.com/tapmodo/Jcrop
https://fengyuanchen.github.i...

镰月
313 声望13 粉丝

它的优秀之处并非原创,它的原创之处并不优秀。