I'm working on an image resizing function. i'm supposed to downsize the image by 25% each time until it meets the required size. I tried to debug my code but it doesn't seem to trigger another load when the image is already loaded and I change the src.
generateData(data: File) {
const image = new Image();
image.src = URL.createObjectURL(data);
return Observable.fromEvent(image, 'load').map(e => {
let newWidth: number = image.width;
let canvas = document.createElement('canvas');
const ctx = canvas.getContext("2d");
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
while(newWidth > 2000) {
canvas = document.createElement('canvas');
const ctx = canvas.getContext("2d");
newWidth = newWidth * 0.75 >= 2000 ? newWidth * 0.75 : 2000;
const scale = newWidth / image.width;
image.width = newWidth;
image.height = image.height * scale;
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
image.src = canvas.toDataURL("image/png", 1);
}
const binStr = atob(canvas.toDataURL("image/png", 0.8).split(',')[ 1 ]);
const arr = new Uint8Array(binStr.length);
for(let i = 0; i < binStr.length; i++) { arr[ i ] = binStr.charCodeAt(i); }
const blob = new Blob([ arr ], { type: 'image/png' });
return new File([ blob ], data.name);
});
}