Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to resize base64 image in angular

i try to resize base64 image But I did not find an answer. I tried canvas but did not answer. I do not know why ... This was the code

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

Does anyone know any other way or knows what the problem is?

like image 529
mahdi aghasi Avatar asked Jul 10 '19 09:07

mahdi aghasi


1 Answers

Add this helper function outside of the given component:

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

Then call like so:

compressImage(base64, 100, 100).then(compressed => {
  this.resizedBase64 = compressed;
})
like image 178
Maximillion Bartango Avatar answered Oct 01 '22 19:10

Maximillion Bartango