H5 call the local camera and compress the upload (intercepted from the angular ionic project)

Source: Internet
Author: User

HTML section

1   <Divclass= "List_upload Item Bg_white">2       <Divclass= "Itemimg pic_upload"ng-repeat= "Item in thumb">3           <!--use the angular cycle to display images that are stored in a thumb -4           <imgng-src= "{{item.imgsrc}}"alt=""/>5           <spanclass= "Itemimgclose"ng-if= "Item.imgsrc"Ng-click= "Img_del ($index)"><Iclass= "Ion-android-close"></I></span>6       </Div>7       <Divclass= "Item_file"ng-repeat= "Item in Thumb_default"ng-if= "Addimg">8            <!--The reason for this is to write a loop in case you need multiple ' plus ' boxes later -9            <Divclass= "Item Pic_upload"> <Iclass= "icon Ion-android-add"></I>TenAdd a picture<inputtype= "File"ID= "One-input"Accept= "image/*"File-model= "Images"onchange= "Angular.element (this)." Scope (). Img_upload (this.files) "/> One            </Div> A        </Div> -</Div>

JS section

$scope. Reader =NewFileReader ();//Create a FileReader interface$scope. Thumb = {};//base64 for storing pictures$scope. Imagnmae = []; //monitor changes in photosConsole.log ($scope. thumb); $scope. Thumb_default= {//box for looping the default ' plus ' to add a picture1111:{}      }; //canvas for compressing pictures      varCanvas = document.createelement ("Canvas"); varCTX = Canvas.getcontext (' 2d '); //Tile Canvas      varTcanvas = document.createelement ("Canvas"); varTctx = Tcanvas.getcontext ("2d"); //ionic POST RequestHead      varTRANSFN =function(obj) {return$httpParamSerializerJQLike (obj); }, Postcfg={headers: {' Content-type ': ' application/x-www-form-urlencoded; Charset=utf-8 '}, TRANSFORMREQUEST:TRANSFN}; varFlag = 0;//flag Bit$scope. addimg =true; varMaxSize = 100*1024;//image size is 100kb$scope. Img_upload =function(Files) {//function of single commit pictureflag++; varSize = files[0].size/1024 > 1024? (~ ~ (files[0].size/1024/1024))/ten + "MB": ~ ~ (files[0].size/1024) + "KB"; $scope. Guid= (NewDate ()). ValueOf ();//Create a random number with a timestamp as the key name$scope. Reader.readasdataurl (Files[0]);//FileReader method, turn the picture into a base64$scope. Reader.onload =function(EV) {$scope. $apply (function() {$scope. thumb[$scope. Guid]={imgSrc:ev.target.result,//Receive Base64            }          }); //call to upload a picture          varresult = This. Result; varIMG =NewImage (); IMG.SRC=result; if(Result.length <=maxSize) {Upload (result, files[0].type); return; }          //compress the picture after it is loaded, then upload          if(Img.complete) {callback (); } Else{img.onload=callback; }          functioncallback () {vardata =Compress (IMG); Upload (data, files[0].type); IMG=NULL;        }        }; //Judging the number of pictures        if(Flag >= 3) {$scope. addimg=false;      }      }; $scope. Img_del=function(key) {//Delete , delete when the thumb and the image data inside the form are deleted, to avoid the submission of unnecessaryflag--;        Console.log (key); varGuidarr = [],imgid = [];  for(varPinch$scope. Thumb)        {Guidarr.push (P); }        Delete$scope. Thumb[guidarr[key]];//Delete a picture         for(varSinch$scope. Imagnmae)        {Imgid.push (s); }        Delete$scope. Imagnmae[imgid[key]];//Delete Picture ID        if(Flag < 3) {$scope. addimg=true;       }      }; //use canvas to compress large pictures      varCompress =function(IMG) {varInitsize =img.src.length; varwidth =Img.width; varHeight =Img.height; //if the picture is larger than 4 million pixels, calculate the compression ratio and press the size below 4 million        varratio; if((ratio = width * height/4000000) > 1) {ratio=math.sqrt (ratio); Width/= ratio;        Height/= ratio; }Else{ratio= 1; } canvas.width=width; Canvas.height=height; //Spread the backgroundCtx.fillstyle = "#fff"; Ctx.fillrect (0, 0, Canvas.width, canvas.height); //If the picture pixel is greater than 1 million, use tiles to draw        varcount; if((count = width * height/1000000) > 1) {Count= ~ ~ (math.sqrt (count) + 1);//calculate how many tiles to divide into          //Calculate the width and height of each tile          varNW = ~ ~ (Width/count); varNH = ~ ~ (Height/count); Tcanvas.width=NW; Tcanvas.height=NH;  for(vari = 0; I < count; i++) {             for(varj = 0; J < Count; J + +) {tctx.drawimage (img, i* NW * ratio, J * nh * ratio, NW * ratio, NH * ratio, 0, 0, NW, NH); Ctx.drawimage (Tcanvas, I* NW, J *NH, NW, NH); }          }        } Else{ctx.drawimage (img,0, 0, width, height); }        //for minimum compression        varNdata = Canvas.todataurl (' Image/jpeg ', 0.1); //Console.log (' Pre-compression: ' + initsize);        //Console.log (' after compression: ' + ndata.length ');        //Console.log (' compression ratio: ' + ~ ~ (initsize-ndata.length)/initsize) + "%");Tcanvas.width = Tcanvas.height = Canvas.width = Canvas.height = 0; returnNdata;     }; //image upload,      varUpload =function(basestr,type) {varText = Basestr.split (",") [1];//intercept picture byte stream        varobj ={"Parameter name": "Parameter"        }; $http. Post ("Interface link", obj,postcfg). Success (function(data) {}). Error (function(Err) {$scope. Loadmore=true; $ionicLoading. Show ({Template:"The data could not be loaded. Please try again later. ", Duration:2000          });      }); };

Effect Show

Reference Links:

1, https://github.com/whxaxes/node-test/blob/master/server/upload/index_2.html

2, Https://github.com/whxaxes/node-test/blob/master/server/upload/upload_2.js

3, http://www.cnblogs.com/jach/p/5734920.html

H5 call the local camera and compress the upload (intercepted from the angular ionic project)

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.