js : resize image as base64

علی ذوالفقار
1402/04/17 14:42:13 (168)
const resize_image_as_base64 = async (file) => {
    return new Promise((resolve, reject) => {
        var resizedImage;
        if (file.type.match(/image.*/)) { // if file is an image 
            // Load the image
            var reader = new FileReader();
            reader.onload = function (readerEvent) { // create reader onload event handler 
                var image = new Image();
                image.onload = function (imageEvent) { // creat image onload event handler  
                    var canvas = document.createElement('canvas'),
                        max_size = 1200,
                        width = image.width,
                        height = image.height;
                    if (width > height) {
                        if (width > max_size) {
                            height *= max_size / width;
                            width = max_size;
                        }
                    } else {
                        if (height > max_size) {
                            width *= max_size / height;
                            height = max_size;
                        }
                    }
                    canvas.width = width;
                    canvas.height = height;
                    canvas.getContext('2d').drawImage(image, 0, 0, width, height); // draw image on canvas 
                    resizedImage = canvas.toDataURL('image/jpeg');
                    resolve(canvas.toDataURL('image/jpeg'));
                }

                image.src = readerEvent.target.result; // trigger image load event 
            }
            reader.readAsDataURL(file); // trigger reader load event 
        }
    });
}
Back