🌑

ArsFy.

How to choose image and crop into the square avatar

It will to crop choose image to square image and output binary


const getSqiareImageBlob = (file) => {
    return new Promise((resolve, reject) => {
        let URL = window.URL || window.webkitURL;
        let imgURL = URL.createObjectURL(file);
        let img = new Image();
        img.src = imgURL;
        img.onload = async () => {
            const canvas = document.createElement('canvas');

            let wh = 0; let dx = 0; let dy = 0;
            if (img.naturalHeight > img.naturalWidth) {
                wh = img.naturalWidth;
                dy = (img.naturalHeight - img.naturalWidth) / 2
            } else {
                wh = img.naturalHeight;
                dx = (img.naturalWidth - img.naturalHeight) / 2
            }

            canvas.height = wh;
            canvas.width = wh;

            const ctx = canvas.getContext('2d');

            ctx.drawImage(img, dx, dy, wh, wh, 0, 0, wh, wh);
            const url = canvas.toDataURL('image/webp');

            resolve(await (await fetch(url)).blob());
        }
    })
}

How to use?

...

<input type="file" id="avatarInput" />

<script>
    document.getElementById("avatarInput").onchange = async (e) => {
        let files = e.target.files, file;
        if (files && files.length > 0) {
            file = files[0];

            let imageBlob = await getSqiareImageBlob(file);
        }
    }
</script>

...

— Jul 5, 2022