mah*_*asi 8 base64 resize typescript angular
我尝试调整 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();
Run Code Online (Sandbox Code Playgroud)
有没有人知道任何其他方式或知道问题是什么?
Max*_*Max 16
在给定组件之外添加此辅助函数:
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);
})
}
Run Code Online (Sandbox Code Playgroud)
然后像这样调用:
compressImage(base64, 100, 100).then(compressed => {
this.resizedBase64 = compressed;
})
Run Code Online (Sandbox Code Playgroud)