Business background: Private messages chat, need to send pictures, but the picture is too large to compress processing. At this point only the picture URL, you can use the following methods: Canvasdataurl (URL, target image width, image to display the parent element of the area)
Note: This file contains the case of Input-file uploading pictures (call photocompress)
//Compress PicturesExportdefault{methods:{//This method is called directly only in the case of BLOB or file-form data //file: Files, W: Target width, objdiv: Target container to be placed after compressionphotocompress (file, W, objdiv) {varReady =NewFileReader ()//asynchronous file read mechanismReady.readasdataurl (file)//Picture PreviewReady.onload =function(){ varRe = This. Result This. Canvasdataurl (Re, w, Objdiv)}},//This method is called directly by the picture URL, re is the URL addressCanvasdataurl (Re, w, Objdiv) {varNewimg =NewImage () newimg.src=Revarimgwidth, ImgHeight, OffsetX= 0, OffsetY= 0//The function of the image is executed synchronously in the onload event of IMG and can be drawn on one side of theNewimg.onload =function(){ varimg = document.createelement ("img") Img.src=newimg.src imgwidth=img.width imgheight=Img.heightvarNewheight = Math.Round (ImgHeight * w/imgwidth)//Calculate the compressed picture height proportionally varCanvas = document.createelement ("Canvas") Canvas.width=W canvas.height=NewheightvarCTX = Canvas.getcontext (' 2d ') //Clearrect (x,y,width,height) //parameter Description: The horizontal ordinate of the beginning of the x, y rectangle, width, height for rectangle width heightCtx.clearrect (0,0, W,newheight)//Reset picture width height to compressed widthImgWidth =W imgheight=Newheight//drawImage (image,x,y,w,h) //parameter Description: The Image-image object, x, y is the starting coordinate of the image in the canvas when it is drawn. W, h indicates the width and height of the image when drawing //This method can also copy a picture area: DrawImage (IMAGE,SX,SY,SW,SH,DX,DY,DW,DH) //parameter Description: Image-image object, SX, SY is copied from the source image from the beginning of the area of the horizontal ordinate, SW, SH when the width of the copied area of the height //dx, DY is the starting horizontal ordinate of the copied target image in the canvas, DW,DH is the width of the copied target image.ctx.drawimage (img,offsetx,offsety,imgwidth,imgheight)//var base64 = canvas.todataurl (' img/png ', 0.7)//parameter indication: Specified picture type, picture quality //if (typeof objdiv = = = = ' object ') {objdiv.appendchild (Canvas)//Console.log (base64) //} else if (typeof objdiv = = = ' function ') { //Objdiv (base64) // } } } }}
If you have any questions, please indicate ~
WebSocket when chatting, image compression processing (URL or input-file)