The idea is to sample the picture on the canvas, and then use the Canvas.todataurl method to get the Base64 string to achieve compression.
1.base64 to binary files
/** * Dataurl to BLOB, ref to https://gist.github.com/fupslot/5015897 * @param Datauri * @returns {blob}*/functionDatauritoblob (Datauri) {varbyteString = Atob (Datauri.split (', ') [1]); varmimestring = Datauri.split (', ') [0].split (': ') [1].split (';') [0]; varAB =NewArrayBuffer (bytestring.length); varIA =NewUint8array (AB); for(vari = 0; i < bytestring.length; i++) {Ia[i]=bytestring.charcodeat (i); } return NewBlob ([ab], {type:mimestring});}
2. Compression parameters (Picture object, quality, output format) returns the compressed Picture object
functionCompress (source_img_obj, quality, Output_format) {varMime_type = "Image/jpeg"; if(output_format!=undefined && output_format== "PNG") {Mime_type= "Image/png"; } varCVS = document.createelement (' Canvas '); //Naturalwidth The width of the real pictureCvs.width =Source_img_obj.naturalwidth; Cvs.height=Source_img_obj.naturalheight; varCTX = Cvs.getcontext ("2d"). DrawImage (source_img_obj, 0, 0); varNewimagedata = Cvs.todataurl (Mime_type, quality/100);varResult_image_obj =NewImage (); RESULT_IMAGE_OBJ.SRC=Newimagedata; returnresult_image_obj;}
3. Main process
- Acquiring and Reading picture objects
- Create
canvas,
dimensions Set the compressed picture size
- Call the
drawImage
method to draw the picture into the canvas
- Called
canvas
to toDataURL,
fetch the base64
data in the format
- Call the Datauritoblob method to a binary file, and then construct
FormData
the data that fills the binary file and commit it by ajax
the way
var file = e.target.files[0];varReader =NewFileReader ();//Read file object Reader.onload= (function(thefile) {varimg = document.getElementById ("img-fileupload_compress")//onload and OnloadendvarQuality = 10;//Picture quality 1-100IMG.SRC=Event.target.result//reader.resultwindow.settimeout (function(){varImgobj =Compress (img,quality)//Compressed picturevarsrc =imgobj.src;//The Base64 format of the image can be directly used as the SRC attribute value of img img.src=src;varFile =Datauritoblob (SRC);//Turn binary file.filename= Math.Round (Math.random () *100000000000000,0) + ". jpg";//Tune Upload interface},1)}); Reader.readasdataurl (file) ;
Front-end preview picture and H5canvas compressed image upload