search
HomeWeb Front-endJS TutorialImage compression and uploading using HTML5

This time I will bring you the use of HTML5 to compress and upload images. What are the precautions for implementing image compression and upload in HTML5? The following is a practical case, let's take a look.

canvas compression

Using a ready-made library on github:

https://github.com/stomita/ios-imagefile-megapixel, I have to worship stomita This great god. The general idea is to sample the image and display it on the canvas, and then use the canvas.toDataURL method to get the base64string to achieve compression. For example, after the input element triggers the change event, read the file inside and perform the operation:

 fileInput = document.getElementById('fileInput'=  file = fileInput.files[0
     mpImg = 
     resImg = document.getElementById('resultImage'
After the compression is completed, you will get a picture similar to this:

data: Format like image/jpeg has been used a lot, and the background images in many styles are just like this.

There are two points to note. The resImg here is a preview image, which already exists in the document. If you do not need a preview, but just create an img for compression (document.createElement(" img")), which will have one less tagName attribute. You can modify the source code or add this attribute yourself. The source code will judge based on tagName. If it does not exist, an error will be reported:

 MegaPixImage.prototype.render = function (target, options, callback) {
        //....
        target.tagName = target.tagName || "IMG"; //加上这一句        var tagName = target.tagName.toLowerCase();        if (tagName === 'img') {
            target.src = renderImageToDataURL(this.srcImage, opt, doSquash);
        } else if (tagName === 'canvas') {
            renderImageToCanvas(this.srcImage, target, opt, doSquash);
        }        if (typeof this.onrender === 'function') {            this.onrender(target);
        }        if (callback) {
            callback();
        }        if (this.blob) {            this.blob = null;
            URL.revokeObjectURL(this.srcImage.src);
        }
    };
In addition, this is a time-consuming operation. If multiple pictures are compressed, it cannot be called directly. It needs to be slightly transformed, otherwise it will cause The previous picture enters the later picture without being compressed.

 fileSelected: function () {                    var files = $("#fileImage")[0].files;                    var count = files.length;
                    console.log("共有" + count + "个文件");                    for (var i = 0; i  1024 * 1024 * 2) {
                            console.log("图片大于2M,开始进行压缩...");
                            (function(img) {                                var mpImg = new MegaPixImage(img);                                var resImg = document.createElement("img");
                                resImg.file = img;
                                mpImg.render(resImg, { maxWidth: 500, maxHeight: 500, quality: 1 }, function() {
                                  //do some thing
                                });
                            })(item);
                        } 
                        core.previewImage(item);
                    }
                },
Upload processing

1. Directly post base64 string

  uploadBase64str: function (base64Str) {
                    var formdata = new FormData();
                    formdata.append("base64str", base64Str);                    var xhr = new XMLHttpRequest();
                    xhr.upload.addEventListener("progress", function (e) {                        var percentComplete = Math.round(e.loaded * 100 / e.total);
                        para.onProgress(percentComplete.toString() + '%');
                    });
                    xhr.addEventListener("load", function (e) {
                        para.uploadComplete(xhr.responseText);
                    });
                    xhr.addEventListener("error", function (e) {
                        para.uploadError(e);
                    });
                    xhr.open("post", para.base64strUrl, true);                    xhr.send(formdata);
                },
For example, here base64strUrl is /home/MUploadImgBase64Str, MVC

ControllerThe method is as follows:

 [HttpPost]        public ActionResult MUploadImgBase64Str(string base64str)
        {            try
            {                var imgData = base64str.Split(',')[1];                //过滤特殊字符即可   
                string dummyData = imgData.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+");                if (dummyData.Length % 4 > 0)
                {
                    dummyData = dummyData.PadRight(dummyData.Length + 4 - dummyData.Length % 4, '=');
                }                byte[] byteArray = Convert.FromBase64String(dummyData);                using (System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArray))
                {                    var img = System.Drawing.Image.FromStream(ms);                    var path = "~/Content/UploadFiles/mobile/";                    var uploadpath = Server.MapPath(path);                    if (!Directory.Exists(uploadpath))
                    {
                        Directory.CreateDirectory(uploadpath);
                    }                    var saveName = uploadpath + “stoneniqiu” + ".jpg";
                    img.Save(saveName);                    return Json(saveName);
                }
            }            catch (Exception e)
            {                return Json(e.Message);
            }
        }
Pictures of several MB can be compressed to tens of kilobytes or hundreds of kilobytes. Of course, if the width, height and quality are set too small, the picture will be very distorted. How to get this string? There are two methods, one is to read src directly:

 var base641 = resImg.src;
and the other is to use canvas conversion:

 function getBase64Image(img) {                var canvas = document.createElement("canvas");
                canvas.width = img.width;
                canvas.height = img.height;                var ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0, img.width, img.height);                var dataURL = canvas.toDataURL("image/jpeg");                return dataURL;                // return dataURL.replace("data:image/png;base64,", "");            } var base64 = getBase64Image(resImg);
For the same picture, the string sizes obtained by the two are different, but the picture I can't tell any difference in quality.

For example, for a 2M picture, the string size read through the getBase64Image method is only 64k, but the size read directly by src is 270k, and the resulting pictures are smaller. . The following are the corresponding images of the original image (2.2M), base64 (48k), and src (202k).

getBase64Image obtains a smaller base64 string through the toDataURL of canvas.

2. You can also convert the blob object on the front end and then post it to the backend

 
                 byteString = atob(dataUrl.split(',')[1
 ab =  ia =  ( i = 0; i 3. If it is not compressed, install it directly into formdata and send it to the backend. <p style="text-align: left;"></p><pre class="brush:php;toolbar:false">   uploadFile: function (file) {
                    console.log("开始上传");                    var formdata = new FormData();
                    formdata.append(para.filebase, file);//这个名字要和mvc后台配合
                    var xhr = new XMLHttpRequest();
                    xhr.upload.addEventListener("progress", function (e) {                        var percentComplete = Math.round(e.loaded * 100 / e.total);
                        para.onProgress(percentComplete.toString() + '%');
                    });
                    xhr.addEventListener("load", function (e) {
                        para.uploadComplete(xhr.responseText);
                    });
                    xhr.addEventListener("error", function (e) {
                        para.uploadError(e);
                    });
                    xhr.open("post", para.url, true);                        xhr.send(formdata);
                },
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to prevent JS bubbling and the browser’s default behavior

js and canvas composite images Create a WeChat public account poster function

Use of checkbox in jQuery

Can the DataTable plug-in realize asynchronous loading? ?

The above is the detailed content of Image compression and uploading using HTML5. 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
html5的div一行可以放两个吗html5的div一行可以放两个吗Apr 25, 2022 pm 05:32 PM

html5的div元素默认一行不可以放两个。div是一个块级元素,一个元素会独占一行,两个div默认无法在同一行显示;但可以通过给div元素添加“display:inline;”样式,将其转为行内元素,就可以实现多个div在同一行显示了。

html5中列表和表格的区别是什么html5中列表和表格的区别是什么Apr 28, 2022 pm 01:58 PM

html5中列表和表格的区别:1、表格主要是用于显示数据的,而列表主要是用于给数据进行布局;2、表格是使用table标签配合tr、td、th等标签进行定义的,列表是利用li标签配合ol、ul等标签进行定义的。

html5怎么让头和尾固定不动html5怎么让头和尾固定不动Apr 25, 2022 pm 02:30 PM

固定方法:1、使用header标签定义文档头部内容,并添加“position:fixed;top:0;”样式让其固定不动;2、使用footer标签定义尾部内容,并添加“position: fixed;bottom: 0;”样式让其固定不动。

HTML5中画布标签是什么HTML5中画布标签是什么May 18, 2022 pm 04:55 PM

HTML5中画布标签是“<canvas>”。canvas标签用于图形的绘制,它只是一个矩形的图形容器,绘制图形必须通过脚本(通常是JavaScript)来完成;开发者可利用多种js方法来在canvas中绘制路径、盒、圆、字符以及添加图像等。

html5中不支持的标签有哪些html5中不支持的标签有哪些Mar 17, 2022 pm 05:43 PM

html5中不支持的标签有:1、acronym,用于定义首字母缩写,可用abbr替代;2、basefont,可利用css样式替代;3、applet,可用object替代;4、dir,定义目录列表,可用ul替代;5、big,定义大号文本等等。

html5废弃了哪个列表标签html5废弃了哪个列表标签Jun 01, 2022 pm 06:32 PM

html5废弃了dir列表标签。dir标签被用来定义目录列表,一般和li标签配合使用,在dir标签对中通过li标签来设置列表项,语法“<dir><li>列表项值</li>...</dir>”。HTML5已经不支持dir,可使用ul标签取代。

Html5怎么取消td边框Html5怎么取消td边框May 18, 2022 pm 06:57 PM

3种取消方法:1、给td元素添加“border:none”无边框样式即可,语法“td{border:none}”。2、给td元素添加“border:0”样式,语法“td{border:0;}”,将td边框的宽度设置为0即可。3、给td元素添加“border:transparent”样式,语法“td{border:transparent;}”,将td边框的颜色设置为透明即可。

html5是什么意思html5是什么意思Apr 26, 2021 pm 03:02 PM

html5是指超文本标记语言(HTML)的第五次重大修改,即第5代HTML。HTML5是Web中核心语言HTML的规范,用户使用任何手段进行网页浏览时看到的内容原本都是HTML格式的,在浏览器中通过一些技术处理将其转换成为了可识别的信息。HTML5由不同的技术构成,其在互联网中得到了非常广泛的应用,提供更多增强网络应用的标准机。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor