前端canvas实现图片压缩及转base64

  1. 实现思路: 先取得图片,再用canvas转成base64
  2.  //上传头像图片   
  3. function uploadHead(imgPath) {  
  4.     console.log("imgPath = " + imgPath);  
  5.     var image = new Image();  
  6.     image.onload = function() {  
  7.         var imgData = getBase64Image(image);  
  8.         /*在这里调用上传接口*/  
  9.         mui.ajax($serverPath + "app/modifyHead", {  
  10.             data: {  
  11.                 'imgData': imgData,  
  12.                 'userId': plus.storage.getItem("userId")  
  13.             },  
  14.             dataType: 'json',  
  15.             type: 'post',  
  16.             timeout: 10000,  
  17.             success: function(data) {  
  18.                 if(data.result == 'yes') {  
  19.                     $newHead = data.newHeadPath;  
  20.                     console.log('上传成功!!!!!!!!!!' + $newHead);  
  21.                     plus.storage.setItem("userHead", $newHead);  
  22.                     mui.toast("头像修改成功!");  
  23.                 } else {  
  24.                     mui.toast("头像上传失败!");  
  25.                 }  
  26.             },  
  27.             error: function(xhr, type, errorThrown) {  
  28.                 mui.toast('网络异常,请稍后再试!');  
  29.             }  
  30.         });  
  31.     }  
  32.     image.src = imgPath;  
  33.     image.style.width = "60px";  
  34.     image.style.height = "60px";  
  35.     console.log("haha");  
  36. }  
  37. //将图片压缩转成base64   
  38. function getBase64Image(img) {  
  39.     var canvas = document.createElement("canvas");  
  40.     var width = img.width;  
  41.     var height = img.height;  
  42.     // calculate the width and height, constraining the proportions   
  43.     if(width > height) {  
  44.         if(width > 100) {  
  45.             height = Math.round(height *= 100 / width);  
  46.             width = 100;  
  47.         }  
  48.     } else {  
  49.         if(height > 100) {  
  50.             width = Math.round(width *= 100 / height);  
  51.             height = 100;  
  52.         }  
  53.     }  
  54.     canvas.width = width; /*设置新的图片的宽度*/  
  55.     canvas.height = height; /*设置新的图片的长度*/  
  56.     var ctx = canvas.getContext("2d");  
  57.     ctx.drawImage(img, 0, 0, width, height); /*绘图*/  
  58.     var dataURL = canvas.toDataURL("image/png", 0.8);  
  59.     return dataURL.replace("data:image/png;base64,""");  
  60. }  
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值