您好,欢迎访问一九零五行业门户网

jQuery实现图片上传和裁剪插件Croppie_jquery

在很多应用需要上传本地图片然后再按尺寸适当裁剪以符合网站对图片尺寸的要求。最常见的就是各用户系统要求用户上传和裁剪头像的应用。今天我给大家介绍的是一款基于html5和jquery的图片上传和裁剪插件,它叫croppie。
运行效果图:
html
首先我们将相关js和css文件载入head中。

接下来我们在页面上放置一个图片上传按钮,我们可以用css将type=file的文件选择控件转成按钮样式。选择完图片后,在#upload-demo展示上传图片,以及调用裁剪插件croppie。#result用来展示裁剪后的图片。
上传
裁剪

css
使用以下css代码,我们很完美的将选择文件的控件转成按钮的样式,其实就是将type=file透明度设成0,然后和button重叠。此外,我们先将图片裁剪区域.crop设置为不可见,等选择文件后再显示。
button, 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; } button:focus { outline: 0; } .file-btn { position: relative; } .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; } .crop{display:none}
jquery
首先利用html5的filereader api读取本地文件,然后$('#upload-demo').croppie()调用了croppie插件。croppie的选项viewport:可以设置所裁剪图片的宽度和高度,以及类型(圆形或方形);选项boundary是图片的外围尺寸。它还有参数mousewheelzoom:是否支持鼠标滚轮缩放图像;showzoom:是否展示缩放条工具;update:回调函数。
$(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 } }); $('#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 = ''; } $(#result).html(html); } });
当点击“裁剪”按钮后,再次调用croppie的result的方法,返回一张裁剪后的图片,并显示在#result中。
以上就是jquery实现图片上传和裁剪的主要过程,希望对大家学习图片上传和裁剪技术有所帮助。
其它类似信息

推荐信息