1

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

1 Answers1

2

Yes each time you change the src if that is a valid url then you'll get .onload event :

image.onload event and browser cache

https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/image.onload

https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images

document.addEventListener("DOMContentLoaded", function() {
  var $image = document.getElementById("image");
  $image.onload = function() {  console.log("Image loaded."); }
  setTimeout( () => $image.src = "http://finevintagedesign.com/sites/default/"+
                              "files/styles/uc_product_full/public/vo539b09c.jpg" , 3333 );
  // This one set to the same URl 
  setTimeout( () => $image.src = "http://finevintagedesign.com/sites/default/"+
                              "files/styles/uc_product_full/public/vo539b09c.jpg" , 5555 );
});
img {
  width:111px;
  height:111px;
}
<img id="image" src="http://finevintagedesign.com/sites/default/files/styles/uc_product_full/public/vo539b09a.jpg"/>
nullqube
  • 2,959
  • 19
  • 18