前言
图片裁剪上传,不仅是一个很贴合用户体验的功能,还能够统一特定图片尺寸,优化网站排版,一箭双雕。
需求就是那么简单,在浏览器里裁剪图片并上传到服务器。
我第一个想到的方法就是,将图片和裁剪参数(x,y,scale,rotate)一并上传给服务器,服务器来做图片处理,so easy。
但是,这并不符合潮流发展的方向: 能在前端做的处理,就放前端做吧。
与潮流妥协的结果就是,前端越来越复杂。
一开始我并不认为浏览器能够读取并生成图片。想想看啊,要做"点击复制"的这样简单的功能,都需要借助 Flash 的浏览器,权限哪有那么大。
参阅各类网站,只要把图片放在本地处理的,基本上都借用了Flash。随便抄一个吧,没有API,就算能修改图片,上传路径都不知道怎么改。更关键的是,我对Flash一窍不通。
好在我们的网站已经完全抛弃了IE9以下的浏览器,只兼容现代HTML5浏览器。(连Opera和微软都开始走Webkit内核的路线了,潮流就是跟着Chrome走)只能寄希望与HTML5,于是钻研了一番,发现如下流程可行。
st=>start: 原图片 File 对象e=>end: 上传裁剪后的Blob对象op=>operation: 初始化Cropper 图片Base64预览op1=>operation: 根据Cropper裁剪参数绘制Canvas(Base64)op2=>operation: Base64转Blob对象st->op->op1->op2->e
以下将对每个环节详解。
获取原图片 File 对象
每个图片文件处理的开始,都是由onchange事件开始
<script> function handler(e){ var originPhoto = e.target.files[0]; // IE10+ 单文件上传取第一个 window.originFileType = originPhoto.type; //暂存图片类型 window.originFileName = originPhoto.name; //暂存图片名称 ... }</script><input type="file" name="demo" onchange='handler(event)' accept="image/*" ><img id="preview" alt="无需Flash实现图片裁剪--HTML5中级进阶_html/css_WEB-ITnose" ><button onclick="cropAndUpload()">确定并上传</button>
初始化Cropper
在这里介绍一个非常好用的库 cropper.js
https://github.com/fengyuanchen/cropper
生成遮罩、获取裁剪参数、输出canvas ... 而且绝对轻量级,压缩后的css和js代码只有30KB。他是基于JQuery的,引入JQuery可能还要再大点。不过现在哪个网站没有在用JQuery呢?
兼容IE9+,移动端体验良好,能够响应触摸缩放,拖动。以下是安卓4.4 原生浏览器中的预览图
function handler(event){ ... var URL = window.URL || window.webkitURL , originPhotoURL; originPhotoURL = URL.createObjectURL(originPhoto); //Base64 $('#preview').cropper({ aspectRatio: 1 / 1, // 固定裁剪比例1:1,裁剪后的图片为正方形 }).cropper('replace', originPhotoURL); // 动态设置图片预览}
绘制Canvas
cropper.js 提供了生成Canvas的方法 getCroppedCanvas ,可以指定生成画布的大小。
或者根据 getData 获取裁剪信息(包括旋转和缩放)用 ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) 进行手动绘制。后者自由性高一点,但是既然有现成的方法,那么就直接用好了。
function cropAndUpload(){ // 此处注意,生成的Canvas长宽比应与之前规定的裁剪比例一致 // 否则生成的图片会有失真 var size = { width:100, height:100 } var croppedCanvas = $('#preview').cropper("getCroppedCanvas",size); // 生成 canvas 对象 var croppedCanvasUrl = croppedCanvas.toDataURL(originFileType); // Base64 ...}
应当注意的是 width 和 height 的值并不推荐设置成固定值。裁剪框的大小可能是会超过100 100(比如500 500)的,而实际生成的图片却是100 100,这样的后果就是直接将一个500 500的高清图片,压缩成了100 100的失真图片。同样的,裁剪框小于100 100,生成的图片就会模糊。
Base64 转Blob对象
字符串转为二进制?(前端本来是个做页面的,现在也开始操作文件了。自从有了HTML5,就可以把浏览器当作一个操作系统了)官方并没有出 DataURLtoBlob 的方法,所以只能自己写一个,转化也挺简单:拆解文件类型,将字符数据转成16进制数据存数组,并用数据初始化一个Blob对象。
function dataURLtoBlob(dataurl) { var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while(n--){ u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], {type:mime});}function cropAndUpload(){ ... var croppedBlob = dataURLtoBlob(croppedCanvasUrl); croppedBlob.name = originFileName; // Blob对象没有name // Upload(croppedBlob);}
现在就可以像处理FileObject一样处理 这个blob对象了。
其实在最新的HTML5标准中是支持 HTMLCanvasElement.toBlob(callback, mimeType, quality) 的
croppedCanvas.toBlob(function(croppedBlob){ // Upload(croppedBlob);},originFileType)
绕了一个弯,不过还是学到了东西。
原文作者来自 MaxLeap 团队_UX成员:John王
原文链接: https://blog.maxleap.cn/archives/705

The official account web page update cache, this thing is simple and simple, and it is complicated enough to drink a pot of it. You worked hard to update the official account article, but the user still opened the old version. Who can bear the taste? In this article, let’s take a look at the twists and turns behind this and how to solve this problem gracefully. After reading it, you can easily deal with various caching problems, allowing your users to always experience the freshest content. Let’s talk about the basics first. To put it bluntly, in order to improve access speed, the browser or server stores some static resources (such as pictures, CSS, JS) or page content. Next time you access it, you can directly retrieve it from the cache without having to download it again, and it is naturally fast. But this thing is also a double-edged sword. The new version is online,

The article discusses using HTML5 form validation attributes like required, pattern, min, max, and length limits to validate user input directly in the browser.

This article demonstrates efficient PNG border addition to webpages using CSS. It argues that CSS offers superior performance compared to JavaScript or libraries, detailing how to adjust border width, style, and color for subtle or prominent effect

Article discusses best practices for ensuring HTML5 cross-browser compatibility, focusing on feature detection, progressive enhancement, and testing methods.

The article discusses the HTML <datalist> element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

The article discusses the HTML <meter> element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates <meter> from <progress> and ex

This article explains the HTML5 <time> element for semantic date/time representation. It emphasizes the importance of the datetime attribute for machine readability (ISO 8601 format) alongside human-readable text, boosting accessibilit

The article discusses the HTML <progress> element, its purpose, styling, and differences from the <meter> element. The main focus is on using <progress> for task completion and <meter> for stati


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools
