[H5-compress-image] using canvas to implement JavaScript image compression processing _ Code implementation based on Requirejs modularization

Source: Internet
Author: User
Tags readfile sendfile

There is also the problematic code, the problem is that the processfile ()
Problem: Under Ipone 5c, some image compression processing, uploaded to the server generated file size is 0, that is, blank; define ([' mod/tool/formsubmit '), function (O_formsubmit) {return { Init:function (ID) {var self = this; Self.sniff (ID); var $img = '; var $inputField = '; }, Sniff:function (ID) {var self = this; if (window. File && window. FileReader && window. FormData) {$inputField = $ (' # ' + ID); $inputField. On (' Change ', function (e) {var file = E.target.files[0]; if ($ ('. C-img-wrap '). Length >= 9) {Hnb.ui.showError (' cannot upload more than 9 images ', 3000); return; } if (file) {//alert (file.type); if (!file.type) file.type= ' image/jpeg '; if (/^image\//i.test (file. type) {if ($ ("#id_img_list"). Parent (). attr ("ScrollWidth") > $ (Window). Width ()) {$ ("#id_img_list"). Parent (). ScrollLeft ($ ("#id_img_list"). Parent (). attr ("SC Rollwidth ")-$ (window). width ()); } $img = $ (' <a class= "bg c-img-wrap" href= "javascript:void (null);" ><i class= "Pa c-img-close" ></i></a> "). InsertBefore ($ (" #id_last_img_wrap ")); Self.readfile (file); } else {//Hnb.ui.showError (' Please open this page in the browser to upload Pictures ', 3000); $inputField. Val ("); //} } }); $inputField. Val ("); } else {Hnb.ui.showError ("Currently your browser does not support image uploads, please select a different browser to upload. ", 3000); $inputField. Val ("); } }, Readfile:function (file) {var self = this; var reader = new FileReader (); var head = '; Reader.onloadend = function () {//reader.onload = function () {head = READER.RESULT.SUBSTR (0, 20); Alert (' head: ' + head '); Alert (' File_type: ' + file.type); Self.processfile (Reader.result, File.type); } reader.onerror = function () {Hnb.ui.showError (' A network exception occurred during the upload of the picture, please try again later. ', 3000); } reader.readasdataurl (file); }, Processfile:function (Dataurl, fileType) {var = this; var maxWidth = 3120; var maxheight = 4208; var image = new Image (); IMAGE.SRC = Dataurl; Image.onload = function () {var width = image.width; var height = image.height; var shouldresize = (Width &GT MaxWidth) | | (Height > MaxHeight); if (!shouldresize) {//self.submitfile (Dataurl); Self.sendfile (Dataurl, FileType); Return } var Newwidth; var newheight; if (width > height) {newheight = height * (maxwidth/width); Newwidth = MaxWidth; } else {newwidth = width * (maxheight/height); Newheight = MaxHeight; } var canvas = document.createelement (' canvas '); Canvas.width = Newwidth; Canvas.height = Newheight; var context = Canvas.getcontext (' 2d '); Context.drawimage (this, 0, 0, newwidth, newheight); Dataurl = Canvas.todataurl (FileType); alert (dataurl.length); window.location = Dataurl; Self.sendfile (DatauRL, FileType); /* var file = canvas.mozgetasfile ("Foo.png"); var f = document.createelement ("form"); var i = document.createelement ("input"); INPUT element, text I.setattribute (' type ', "file"); I.setattribute (' name ', ' Upfile '); I.setattribute (' value ', dataurl); F.appendchild (i); *///$ ("#id_upfile"). Val (Dataurl); Document.forms[0].upfile.val = Dataurl; window.location = Dataurl; var formData = new FormData (document.forms[0]); Console.log (Document.forms[0]); Console.log (Formdata.get (' upfile ')); Console.log (FormData); Return Formdata.append (' ImageData ', dataurl); Formdata.delete (' upfile '); Console.log ($inputField. files); Formdata.set (' UPFIle ', $inputField. files[0], Dataurl); Self.submitfile ($ (f)); }; Image.onerror = function () {//alert (' There is an error processing your file! '); Hnb.ui.showError (' A network exception occurred during the upload process, please try again later. ', 3000); }; }, Submitfile:function (f) {var = this; Console.log (f); O_formsubmit.create (F, Hnb.www_cgi_url + "/image/saveincrossdomain"). Start (). Done (function (json_msg) {if (j Son_msg.state | | !json_msg.data.real_url) {Hnb.ui.showError ("Upload picture Failed! ", 3000); $img. Remove (); } else {console.log (json_msg.data); $img. Removeclass ("BG"). AddClass ("COMBG"). CSS ("background-image", "url (" + Json_msg.data.real_url + ")"). attr (" Hnb-src ", Json_msg.data.real_url); $img. html ('

 

After modification, the code can be used normally; define ([' mod/tool/formsubmit '], function (o_formsubmit) {return {init:function (ID) {            var = this;            Self.sniff (ID);            var $img = ';        var $inputField = ';            }, Sniff:function (ID) {var self = this; if (window. File && window. FileReader && window.                FormData) {$inputField = $ (' # ' + ID);                    $inputField. On (' Change ', function (e) {var file = E.target.files[0];                        if ($ ('. C-img-wrap '). Length >= 9) {Hnb.ui.showError (' cannot upload more than 9 images ', 3000);                    return;                        } if (file) {//if (!file.type) file.type= ' image/jpeg '; if (/^image\//i.test (File.type)) {if ($ ("#id_img_list"). Parent (). attr ("Scro Llwidth ") &GT $ (window). Width ()) {$ ("#id_img_list"). Parent (). ScrollLeft ($ ("#id_img_li                        St "). Parent (). attr (" ScrollWidth ")-$ (window). width ()); } $img = $ (' <a class= "bg c-img-wrap" href= "javascript:void (null);"                                                ><i class= "Pa c-img-close" ></i></a> "). InsertBefore ($ (" #id_last_img_wrap "));                    Self.readfile (file);            }                }); } else {Hnb.ui.showError ("Currently your browser does not support image uploads, please select a different browser to upload.                ", 3000);            $inputField. Val (");        } $inputField. val (");            }, Readfile:function (file) {var self = this;            var reader = new FileReader ();            var head = '; Reader.onloadend = function () {//reader.onload = function () {//head = reader.result.substr (0                , 20); Self.processfile (reAder.result, File.type); } reader.onerror = function () {Hnb.ui.showError (' A network exception occurred during the upload of the picture, please try again later.                ', 3000);            Return            } reader.readasdataurl (file);        $inputField. Val (");            }, Processfile:function (Dataurl, fileType) {var = this;            var unitsize = 480;            var image = new Image ();            IMAGE.SRC = Dataurl;                Image.onload = function () {var wfactor = image.width/unitsize;                var hfactor = image.height/unitsize;                var minfactor = Math.Round (Math.min (Wfactor, hfactor));                    if (Minfactor < 2) {//self.submitfile (Dataurl);                    Self.sendfile (Dataurl, FileType);                Return                } var newwidth = Image.width/minfactor;                var newheight = Image.height/minfactor; var canvas = Document.creAteelement (' canvas ');                Canvas.width = Newwidth;                Canvas.height = Newheight;                var context = Canvas.getcontext (' 2d ');                Context.drawimage (this, 0, 0, newwidth, newheight);                Dataurl = Canvas.todataurl (FileType);                window.location = Dataurl;            Self.sendfile (Dataurl, FileType);            }; Image.onerror = function () {Hnb.ui.showError (' A network exception occurred during upload of picture processing, please try again later.                ', 3000);            $inputField. Val (");        };            }, Submitfile:function (f) {var = this; O_formsubmit.create (F, Hnb.www_cgi_url + "/image/saveincrossdomain"). Start (). Done (function (json_msg) {if (j Son_msg.state | | !json_msg.data.real_url) {Hnb.ui.showError ("Upload picture Failed!                    ", 3000);                $img. Remove (); } else {$img. removeclass ("BG"). AddClass ("COMBG"). CSS ("Background-image", "uRL ("+ Json_msg.data.real_url +") "). attr (" Hnb-src ", Json_msg.data.real_url);                    $img. html (' 

[H5-compress-image] using canvas to implement JavaScript image compression processing _ Code implementation based on Requirejs modularization

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.