基於vue上傳base64圖片,經過canvas壓縮base64

其實和vue關係不大,和咱們以前作上傳壓縮性質是同樣的 固然下面的代碼是沒有處理ios橫屏拍照的bug的 有興趣的能夠多搜一下  網上都有相應的解答 、、
      var that = this
      if (e.target.files[0]) {
        var file = e.target.files[0]
        var reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = function() {
          img.src = this.result
        }
        var img = new Image,
          width = 1024, //image resize   壓縮後的寬
          quality = 0.8, //image quality  壓縮質量
          canvas = document.createElement("canvas"),
          drawer = canvas.getContext("2d");
        img.onload = function() {
          canvas.width = width;
          canvas.height = width * (img.height / img.width);
          drawer.drawImage(img, 0, 0, canvas.width, canvas.height);
//上傳到七牛雲
var base64 = canvas.toDataURL("image/jpeg", quality); // 這裏就拿到了壓縮後的base64圖片 var pic = base64.split(',')[1]; var url = "http://upload-z2.qiniu.com/putb64/-1"; var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { that.imgs.push(JSON.parse(xhr.responseText).data.key); } } xhr.open("POST", url, true); xhr.setRequestHeader("Content-Type", "application/octet-stream"); xhr.setRequestHeader("Authorization", "UpToken " + ‘七牛雲token’); xhr.send(pic); // 清空文件上傳控件的值 不清理會出現選擇一樣的圖片會沒法觸發input事件了 e.target.value = null; }
相關文章
相關標籤/搜索