如何在 angular 中调整 base64 图像的大小

how to resize base64 image in angular

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

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();

有没有人知道其他方法或知道问题出在哪里?

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

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;
})

尝试在 angular 库/HTML:

中调整 base64 图像大小时,此代码对我有用
<style>
    .scaled {
        width: 150px;
        height: 150px;
        transform-origin: left;
        transform: scale(1);
    }
</style>

<div class="scaled">
 <img src="data:image/png;base64,iVB....."></img>
</div>