首页 > 解决方案 > 如何以角度调整base64图像的大小

问题描述

我尝试调整 base64 图像的大小但我没有找到答案。我尝试了画布但没有回答。我不知道为什么......这是代码

const canvas = document.createElement('canvas'),
             ctx = <CanvasRenderingContext2D>canvas.getContext('2d');
        canvas.width = 100;
        canvas.height = 100;
        const img = new Image();
        img.src = this.SelectedFile.src;
        ctx.drawImage(img , 0, 0, 100, 100);
        this.SelectedFile.src = ctx.canvas.toDataURL();

有谁知道任何其他方式或知道问题是什么?

标签: angulartypescriptbase64resize

解决方案


在给定组件之外添加这个辅助函数:

function compressImage(src, newX, newY) {
  return new Promise((res, rej) => {
    const img = new Image();
    img.src = src;
    img.onload = () => {
      const elem = document.createElement('canvas');
      elem.width = newX;
      elem.height = newY;
      const ctx = elem.getContext('2d');
      ctx.drawImage(img, 0, 0, newX, newY);
      const data = ctx.canvas.toDataURL();
      res(data);
    }
    img.onerror = error => rej(error);
  })
}

然后像这样调用:

compressImage(base64, 100, 100).then(compressed => {
  this.resizedBase64 = compressed;
})

推荐阅读