0

I am creating an image previw and upload page based on this https://demos.phplift.net/javascript-image-compress-using-html5-canvas-file-api/. It is working fine in all web browsers and in android firefox (version 88.1.4) it is not working with images have size greater than 1MB, no issues in android chrome browser. When I checked the image onload (in code it is i.onload()) function is not triggering for larger images in firefox

html

    <form id="upload_form">
            <label for="file">Choose file</label>
            <input type="file" id="fileinput" />
            
        </form>

javascript function is

<script>
    var output_format = null;
    var file_name = null;
    function readFile(evt) {
        var file = evt.target.files[0];
        var reader = new FileReader();
        reader.onload = function(event) {
            var i = document.getElementById("source_image");
            console.log(i);
                i.src = event.target.result;
                i.onload = function(){
                    
                    console.log("Image loaded");
                }
        };
        output_format = file.name.split(".").pop();
        file_name = file.name;
        console.log("Filename:" + file.name);
        console.log("Fileformat:" + output_format);
        console.log("Filesize:" + (parseInt(file.size) / 1024) + " Kb");
        console.log("Type:" + file.type);
        reader.readAsDataURL(file);

        return false;
    }
document.getElementById("fileinput").addEventListener("change", readFile, false);
</script>

Does anyone know why images greater than 1 MB not trigring image onload in firefox?

Sherin
  • 401
  • 1
  • 11
  • 22

1 Answers1

1

Don't use the FileReader... Think this can work:

i.src = URL.createObjectURL(file)
Endless
  • 34,080
  • 13
  • 108
  • 131
  • i was a bit sceptical if such a simple answer would work :P base64 is the worse, work with blobs whenever possible. not against it, Don't forget use canvas.toBlob instead of `canvas.toDataURL` and one more thing. canvas can increase the file size since it has a terrible compression algoritm – Endless Jun 01 '21 at 20:15
  • the only thing canvas can basically do is crop, resize and change quality. when it comes to actually compressing the data then it dose a bad job if it's unchanged... https://stackoverflow.com/questions/51809241/how-to-compress-a-base64-image-to-custom-size/51810740#51810740 – Endless Jun 01 '21 at 20:19