Home  >  Article  >  Web Front-end  >  About HTML5 to implement image compression and upload function

About HTML5 to implement image compression and upload function

不言
不言Original
2018-06-05 14:27:402218browse

The following editor will bring you an in-depth study of the image compression upload function in HTML5. The editor thinks it’s pretty good, so I’d like to share it with you now. I’d also like to give you a reference. Let’s follow the editor and take a look.

In the previous article, we mentioned uploading pictures on the mobile terminal. We know that traffic is still quite expensive now, and the pixels of mobile phones are getting higher and higher. A photo can easily cost several M, so I can't afford to get hurt. 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, Nima js does not have the authority to operate files and compress images. If it cannot 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 we had less to worry about.

Since I got H5, my boss no longer worries about my development.

The previous 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 and assign it Give the newly created picture object, and then throw the picture object onto the canvas canvas.

XML/HTML CodeCopy the content to the 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 draw the picture When you go to 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</span>The position of the upper left corner of the source image on the X-axis of the target canvas.

##dy<span style="font-family:NSimsun"></span>The position of the upper left corner of the source image on the Y-axis of the target canvas.

dWidth<span style="font-family:NSimsun"></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.

dHeight<span style="font-family:NSimsun"></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.

sx<span style="font-family:NSimsun"></span>The X coordinate of the upper left corner of the rectangular selection box of the source image that needs to be drawn into the target context.

sy<span style="font-family:NSimsun"></span>The Y coordinate of the upper left corner of the rectangular selection box of the source image that needs to be drawn into the target context.

sWidth<span style="font-family:NSimsun"></span>The width of the rectangular selection box of the source image that needs to be drawn into the target context. If not specified, the entire rectangle starts from the coordinates sx and sy and ends at the lower right corner of the image.

sHeight<span style="font-family:NSimsun"></span>The height of the rectangular selection box of the source image that needs to be drawn into the target context.

In order to upload the complete image, dx and 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 until the image object is 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(&#39;,&#39;)[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(&#39;myFile&#39;, 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 the 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(&#39;2d&#39;);   
                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(&#39;,&#39;)[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(&#39;myFile&#39;, 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 Canvas绘制时指定颜色与透明度的方法

Use HTML5 Canvas to create a simple masturbation game


The above is the detailed content of About HTML5 to implement image compression and upload function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn