


In-depth study of HTML5 to implement image compression upload function_html5 tutorial skills
The last article mentioned uploading pictures on the mobile terminal. We know that traffic is still quite expensive now. The pixels of mobile phones are getting higher and higher. Taking a picture often takes several megabytes, so we can’t afford it. Although the client can easily compress images and then upload them, our application may still be opened in the browser. What should we do? Image compression. Affected by the previous development thinking on PC, how can Nima js have the authority to operate files, and how can it be qualified to compress images? If it can't be done, your client can fix it. All I can say is that I am still a little bit confused. Under the influence of HTML5, the front-end can do more and more things, and the functions developed are getting higher and higher. Long live H5! This is also the charm of the front end. What was impossible in the past does not mean it is impossible now or in the future. Work hard, Sao Nian!
How to compress images with js? ? ? Subconsciously, I felt that it was impossible to achieve at first, but later I read the information and researched it, and found that it is feasible! Start it!
Let’s first talk about how we uploaded before H5. We usually used plug-ins, flash or simply a file form, so there was less worry and more worry.
Since I got H5, my boss no longer worries about my development.
The last article mentioned that FileReader and FormData are used to upload images. In fact, we can basically preview and upload images mainly using these two. To achieve image compression, we need to use canvas, yes, it is canvas!
The general idea is:
1. Create a picture and a canvas
XML/HTML CodeCopy the content to the clipboard
var image = new Image(), canvas = document.createElement("canvas"), ctx = canvas.getContext('2d');
2. We obtain the image address selected in the input through FileReader Then assign it to the newly created picture object, and then throw the picture object onto the canvas.
XML/HTML CodeCopy content to clipboard
var file = obj.files[0]; var reader = new FileReader();//读取客户端上的文件 reader.onload = function() { var url = reader.result;//读取到的文件内容.这个属性只在读取操作完成之后才有效, 并且数据的格式取决于读取操作是由哪个方法发起的.所以必须使用reader.onload, image.src=url;//reader读取的文件内容是base64,利用这个url就能实现上传前预览图片 ... }; image.onload = function() { var w = image.naturalWidth, h = image.naturalHeight; canvas.width = w; canvas.height = h; ctx.drawImage(image, 0, 0, w, h, 0, 0, w, h); fileUpload(); }; reader.readAsDataURL(file);
It should be noted here that canvas will When drawing a picture on the canvas, you need to determine the size of the canvas and set the parameters of drawImage, as follows:
XML/HTML CodeCopy the content to the clipboard
void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
<span style="font-family:NSimsun">dx<code><span style="font-family:NSimsun">dx</span>
Source image The upper left corner is at the X-axis position of the target canvas.
<span style="font-family:NSimsun">dy<code><span style="font-family:NSimsun">dy</span>
The position of the upper left corner of the source image on the Y-axis of the target canvas.
<span style="font-family:NSimsun">dWidth<code><span style="font-family:NSimsun">dWidth</span>
The width of the image drawn on the target canvas. Allows scaling of drawn images. If not specified, the image width will not scale when drawing.
<span style="font-family:NSimsun">dHeight<code><span style="font-family:NSimsun">dHeight</span>
The height of the image drawn on the target canvas. Allows scaling of drawn images. If not specified, the image height will not scale when drawing.
<span style="font-family:NSimsun">sx<code><span style="font-family:NSimsun">sx</span>
The rectangular selection box of the source image that needs to be drawn into the target context The X coordinate of the upper left corner.
<span style="font-family:NSimsun">sy<code><span style="font-family:NSimsun">sy</span>
The rectangular selection box of the source image that needs to be drawn into the target context The Y coordinate of the upper left corner.
<span style="font-family:NSimsun">sWidth<code><span style="font-family:NSimsun">sWidth</span>
The rectangular selection box of the source image that needs to be drawn into the target context width. If not specified, the entire rectangle starts from the coordinates sx and sy and ends at the lower right corner of the image.
<span style="font-family:NSimsun">sHeight<code><span style="font-family:NSimsun">sHeight</span>
The rectangular selection box of the source image that needs to be drawn into the target context high.
In order to upload the complete image, dx, dy must be set to 0, and dWidth and dHeight must be set to the width and height of the original image. This is why we need to wait for the image object to be downloaded to get its original size. This is critical!
3. Image upload
XML/HTML CodeCopy content to clipboard
function fileUpload() { var data = canvas.toDataURL("image/jpeg", quality); //dataURL 的格式为 “data:image/png;base64,****”,逗号之前都是一些说明性的文字, 我们只需要逗号之后的就行了 datadata = data.split(',')[1]; data = window.atob(data); var ia = new Uint8Array(data.length); for (var i = 0; i < data.length; i++) { ia[i] = data.charCodeAt(i); }; //canvas.toDataURL 返回的默认格式就是 image/png var blob = new Blob([ia], { type: "image/jpeg" }); var fd = new FormData(); fd.append('myFile', blob); var xhr = new XMLHttpRequest(); xhr.addEventListener("load", opts.success, false); xhr.addEventListener("error", opts.error, false); xhr.open("POST", opts.url); xhr.send(fd); }
The key method used here is canvas.toDataURL
XML/HTML CodeCopy content to clipboard
canvas.toDataURL(type, encoderOptions);
官方的说明是The <span style="font-family:NSimsun">HTMLCanvasElement.toDataURL()</span>
method returns a data URI containing a representation of the image in the format specified by the <span style="font-family:NSimsun">type</span>
parameter (defaults to PNG). The returned image is in a resolution of 96 dpi.实际上就是读取canvas画布上图片的数据。其默认是png格式,如果第一个参数type是image/jpeg的话,第二个参数encoderOptions就可以用来设置图片的压缩质量,经过测试,如果是png格式,100%的宽高经过该方法还有可能使图片变大~~~~适得其反,所以我们可以在canvas.drawImage的时候适当设置sWidth和sHeight,比如同比例缩小1.5倍等,图片质量其实并不太影响查看,尤其对尺寸比较大的图片来说。
上面还有比较陌生的方法atob,其作用是做解码,因为图片格式的base64.
XML/HTML Code复制内容到剪贴板
var encodedData = window.btoa("Hello, world"); // encode a string var decodedData = window.atob(encodedData); // decode the string
该方法解码出来可能是一堆乱码,Uint8Array返回的是8进制整型数组。
Blob是存储二进制文件的容器,典型的Blob对象是一个图片或者声音文件,其默认是PNG格式。
XML/HTML Code复制内容到剪贴板
var blob = new Blob([ia], { type: "image/jpeg" });
最后通过ajax将Blob对象发送到server即可。
整个流程大致如上,但是~~~实现以后测试跑来说:“你不是说图片压缩了吗,为什么图片还是上传那么慢!”,哥拿起手机对妹纸演示了一下,明明很快嘛,于是反道“是你手机不行或者网络不好吧,你下载图片看明明变小了,比之前肯定快,你看我秒传”。呵呵,说归说,还是偷偷检查代码,在浏览器中打时间log,对比没压缩之前的,尼玛!!!居然才快了几百毫秒!!折腾了半天,之前的代码也重构了,玩我呢。
细心的大神看了上面的代码估计能猜出问题在哪,没错,获取本地图片长宽尺寸的时候出了问题。
我去,获取本地4M大小的图片尺寸花了3174ms!!,图片越大时间也越久~
JavaScript Code复制内容到剪贴板
image.onload = function() { var w = image.naturalWidth, h = image.naturalHeight; canvas.width = w / 1.5; canvas.height = h / 1.5; ctx.drawImage(image, 0, 0, w, h, 0, 0, w / 1.5, h / 1.5); Upload.fileUpload(type); };
浏览器在本地取图片的时候是没法直接像file.size一样获取其长宽的,只能通过FileReader拿到内容后赋值给新建的image对象,新建的image对象下载需要时间!怎么破?不就是获取本地图片的尺寸吗,难道没有别的办法了?
于是想到了之前研究过的快速获取图片长宽的博文,点击进入 ,demo地址:http://jsbin.com/jivugadure/edit?html,js,output,定时去查询图片加载过程中的高度或者宽度,不用等整个图片加载完毕。
测了下,还是不行,因为定时查询这种方法对常规的server返回的图片有作用,这里图片地址是base64,貌似时间还更久了~哭。
小结一下:
1、用HTML5来压缩图片上传是可行的,在移动端我们不用依赖客户端或者插件,目前主流浏览器支持程度已经很高了。
2、压缩图片一方面是想减少用户上传等待的时间,另外也减少用户为此牺牲的流量,从整体时间来看,因为获取图片尺寸导致多一次下载需要耗时,其实压不压缩时间差别并不是特别大。除非大神们找到合适的方法能够直接获取图片的尺寸,麻烦也告知我一声,万分感谢;
3、既然时间成本差不多,但是我们压缩了图片,减少了图片的大小,减少了流量的消耗,存储空间以及下次获取该图片的时间,所以还是值得的。
补充源代码:
JavaScript Code复制内容到剪贴板
(function($) { $.extend($.fn, { fileUpload: function(opts) { this.each(function() { var $self = $(this); var quality = opts.quality ? opts.quality / 100 : 0.2; var dom = { "fileToUpload": $self.find(".fileToUpload"), "thumb": $self.find(".thumb"), "progress": $self.find(".upload-progress") }; var image = new Image(), canvas = document.createElement("canvas"), ctx = canvas.getContext('2d'); var funs = { setImageUrl: function(url) { image.src = url; }, bindEvent: function() { console.log(dom.fileToUpload) dom.fileToUpload.on("change", function() { funs.fileSelect(this); }); }, fileSelect: function(obj) { var file = obj.files[0]; var reader = new FileReader(); reader.onload = function() { var url = reader.result; funs.setImageUrl(url); dom.thumb.html(image); }; image.onload = function() { var w = image.naturalWidth, h = image.naturalHeight; canvas.width = w; canvas.height = h; ctx.drawImage(image, 0, 0, w, h, 0, 0, w, h); funs.fileUpload(); }; reader.readAsDataURL(file); }, fileUpload: function() { var data = canvas.toDataURL("image/jpeg", quality); //dataURL 的格式为 “data:image/png;base64,****”, 逗号之前都是一些说明性的文字,我们只需要逗号之后的就行了 data = data.split(',')[1]; data = window.atob(data); var ia = new Uint8Array(data.length); for (var i = 0; i < data.length; i++) { ia[i] = data.charCodeAt(i); }; //canvas.toDataURL 返回的默认格式就是 image/png var blob = new Blob([ia], { type: "image/jpeg" }); var fd = new FormData(); fd.append('myFile', blob); var xhr = new XMLHttpRequest(); xhr.addEventListener("load", opts.success, false); xhr.addEventListener("error", opts.error, false); xhr.open("POST", opts.url); xhr.send(fd); } }; funs.bindEvent(); }); } }); })(Zepto);
调用方式:
JavaScript Code复制内容到剪贴板
$(".fileUpload").fileUpload({ "url": "savetofile.php", "file": "myFile", "success":function(evt){ console.log(evt.target.responseText) } });
以上就是深入研究HTML5实现图片压缩上传功能_html5教程技巧的内容,更多相关内容请关注PHP中文网(www.php.cn)!

H5 is HTML5, the fifth version of HTML. HTML5 improves the expressiveness and interactivity of web pages, introduces new features such as semantic tags, multimedia support, offline storage and Canvas drawing, and promotes the development of Web technology.

Accessibility and compliance with network standards are essential to the website. 1) Accessibility ensures that all users have equal access to the website, 2) Network standards follow to improve accessibility and consistency of the website, 3) Accessibility requires the use of semantic HTML, keyboard navigation, color contrast and alternative text, 4) Following these principles is not only a moral and legal requirement, but also amplifying user base.

The H5 tag in HTML is a fifth-level title that is used to tag smaller titles or sub-titles. 1) The H5 tag helps refine content hierarchy and improve readability and SEO. 2) Combined with CSS, you can customize the style to enhance the visual effect. 3) Use H5 tags reasonably to avoid abuse and ensure the logical content structure.

The methods of building a website in HTML5 include: 1. Use semantic tags to define the web page structure, such as, , etc.; 2. Embed multimedia content, use and tags; 3. Apply advanced functions such as form verification and local storage. Through these steps, you can create a modern web page with clear structure and rich features.

A reasonable H5 code structure allows the page to stand out among a lot of content. 1) Use semantic labels such as, etc. to organize content to make the structure clear. 2) Control the rendering effect of pages on different devices through CSS layout such as Flexbox or Grid. 3) Implement responsive design to ensure that the page adapts to different screen sizes.

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

The difference between H5 and HTML5 is: 1) HTML5 is a web page standard that defines structure and content; 2) H5 is a mobile web application based on HTML5, suitable for rapid development and marketing.

The core features of HTML5 include semantic tags, multimedia support, form enhancement, offline storage and local storage. 1. Semantic tags such as, improve code readability and SEO effect. 2. Multimedia support simplifies the process of embedding media content through and tags. 3. Form Enhancement introduces new input types and verification properties, simplifying form development. 4. Offline storage and local storage improve web page performance and user experience through ApplicationCache and localStorage.


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

WebStorm Mac version
Useful JavaScript development 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.

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 Mac version
God-level code editing software (SublimeText3)

Atom editor mac version download
The most popular open source editor
