HTML5 Pre-resize images before uploading

前端 未结 10 2462
野的像风
野的像风 2020-11-22 15:53

Here\'s a noodle scratcher.

Bearing in mind we have HTML5 local storage and xhr v2 and what not. I was wondering if anyone could find a work

10条回答
  •  自闭症患者
    2020-11-22 16:14

    Typescript

    async resizeImg(file: Blob): Promise {
        let img = document.createElement("img");
        img.src = await new Promise(resolve => {
            let reader = new FileReader();
            reader.onload = (e: any) => resolve(e.target.result);
            reader.readAsDataURL(file);
        });
        await new Promise(resolve => img.onload = resolve)
        let canvas = document.createElement("canvas");
        let ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
        let MAX_WIDTH = 1000;
        let MAX_HEIGHT = 1000;
        let width = img.naturalWidth;
        let height = img.naturalHeight;
        if (width > height) {
            if (width > MAX_WIDTH) {
                height *= MAX_WIDTH / width;
                width = MAX_WIDTH;
            }
        } else {
            if (height > MAX_HEIGHT) {
                width *= MAX_HEIGHT / height;
                height = MAX_HEIGHT;
            }
        }
        canvas.width = width;
        canvas.height = height;
        ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, width, height);
        let result = await new Promise(resolve => { canvas.toBlob(resolve, 'image/jpeg', 0.95); });
        return result;
    }
    

提交回复
热议问题