0

Why i cant get my head around promises and async/await I just do not know.

I want to get the base64 contents of an image into a variable inline (and I'm also shinking the image)

async function get_convert_file_to_base_64_and_shrink(file) {
    const reader = new FileReader()

    return new Promise((resolve, reject) => {
        reader.onload = (e) => {
            let image = new Image();
            image.onload = function (imageEvent) {

                // Resize the image
                let 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);
                resolve(canvas.toDataURL('image/jpeg'))
            }
            image.src = reader.result;
        }
        reader.readAsDataURL(file)
    })

}


const base64_image = get_convert_file_to_base_64_and_shrink(file)

Can anyone tell me why the value of base64_image is always null?

I've tried this also but again nothing.

get_convert_file_to_base_64_and_shrink(file).then(r=>{
    base64_image = r
}
Lewis Morris
  • 1,916
  • 2
  • 28
  • 39

0 Answers0