前言
图片裁剪上传,不仅是一个很贴合用户体验的功能,还能够统一特定图片尺寸,优化网站排版,一箭双雕。
需求就是那么简单,在浏览器里裁剪图片并上传到服务器。
我第一个想到的方法就是,将图片和裁剪参数(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 function of HTML is to define the structure and content of a web page, and its purpose is to provide a standardized way to display information. 1) HTML organizes various parts of the web page through tags and attributes, such as titles and paragraphs. 2) It supports the separation of content and performance and improves maintenance efficiency. 3) HTML is extensible, allowing custom tags to enhance SEO.

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software