前端或APP上传图片,图片太大,后端也没必要要原图,
太大的图片,做以下处理。固定大小。
getBase64Image(imgpath:string) { var img = new Image(); //新建一个图片对象 img.src = imgpath; let canvas = document.createElement("canvas"); let w=img.width; let h=img.height; if(h>w) { h=1024; w=w*h/img.height; }else{ w=1024; h=w*h/img.width; } canvas.width = w; canvas.height = h; const ctx = canvas.getContext("2d"); ctx?.drawImage(img, 0, 0, w, h); var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase(); var dataURL = canvas.toDataURL("image/"+ext); this.src=dataURL; console.log(dataURL); return dataURL; }
原文:https://www.cnblogs.com/qgbo/p/14437395.html