Reputation: 378
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?
Upvotes: 12
Views: 18996
Reputation: 1
This code worked for me when trying to resize base64 images in angular libraries / HTML:
<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>
Upvotes: -3
Reputation: 1599
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;
})
Upvotes: 25