[JavaScript]base64和Canvas的互转/图片base64上传

后端JSON返回的为

data:image/jpeg;base64,/9j/........

Base64 ->Canvas

首先页面需要有容器

// or u can have a loop like ngfor or v-for:
                
  setCanvasFun(id, scr) {
    const canvas = document.getElementById(id);
    const img = new Image();
    img.src = scr;
    const myctx = canvas.getContext('2d');
    img.onload = () => {
      myctx.drawImage(img, 0, 0, 300, 150);
    };

  }

Canvas 转64

 setlogo() {
    const dom_pre = document.getElementById('template-preview');
    const canvas = dom_pre.getElementsByTagName('canvas')[0];
    const img = new Image();
    const cur = this;
    img.src = canvas.toDataURL('image/jpeg', 0.8);
    img.onload = () => {
      const mycanvas = document.getElementById('canvas');
      const myctx = mycanvas.getContext('2d');
      myctx.fillStyle = '#fff';
      myctx.fillRect(0, 0, 100, 100);
      myctx.drawImage(img, 0, 0, 100, 100);
      const base64 = mycanvas.toDataURL('image/jpeg', 0.8);
      cur.currentThumbnail = String(base64);
    };
  }

上传功能

HTML:

            
 handleFileInput(files: FileList, dom?) {

    this.fileToUpload = files.item(0);
    const reader = new FileReader();
    reader.readAsDataURL(this.fileToUpload);
    const cur = this;
    reader.onload = function (e) {
      // 压缩
      const obj: any = (e.target as any).result;
      const img = new Image();
      img.src = String(obj);
      img.onload = () => {
        const w = 100;
        const h = 100;
        const quality = 0.8;
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        ctx.fillStyle = '#fff';
        ctx.fillRect(0, 0, w, h);
        ctx.drawImage(img, 0, 0, w, h);
        const base64 = canvas.toDataURL('image/jpeg', quality);
        cur.currentThumbnail = String(base64);
      };

    };

  }

 

你可能感兴趣的:(前端)