1 functionImgToBase64 (file, MaxLen, callBack) {2 varIMG =NewImage ();3 4 varReader =NewFileReader ();//read the file on the client5Reader.onload =function () {6 varurl = reader.result;//The contents of the file to read. This property is valid only after the read operation is complete, and the format of the data depends on which method the read operation originated. So you have to use Reader.onload,7img.src = URL;//Reader read the file content is base64, using this URL can be used to upload a preview image before uploading8 };9Img.onload =function () {Ten //Build Scale One varwidth = img.width, height =Img.height; A //Calculating the zoom ratio - varRate = 1; - if(Width >=height) { the if(Width >maxlen) { -Rate = MaxLen/width; - } -}Else { + if(Height >maxlen) { -Rate = MaxLen/height; + } A }; atImg.width = width *Rate ; -Img.height = Height *Rate ; - //Build Canvas - varCanvas = document.createelement ("Canvas"); - varCTX = Canvas.getcontext ("2d"); -Canvas.width =Img.width; inCanvas.height =Img.height; -Ctx.drawimage (IMG, 0, 0, Img.width, img.height); to varBase64 = Canvas.todataurl (' image/jpeg ', 0.9); + CallBack (base64); - }; the reader.readasdataurl (file); *}
Call Mode:
1$(function () {2$ ("#img"). Change (function () {3 varFile = $ ( This) [0].files[0];//Gets the file selected by the input file control4 5ImgToBase64 (file, 720,function(base64) {6$ ("#img1") [0].SRC =an IMG element is reserved on the base64;//preview page, loaded into Base647$ ("#img1") [0].width = 300;//Set wide height, otherwise it will automatically follow the compressed image width and height setting, it may exceed the expected range.
Upload base64 directly to the server using AJAX, complete8 });9 })Ten})
HTML under the Pure JS implementation picture compression, preview, picture Base64 conversion