0

Consider this javascript code, I wanna be able to manipulate the size of the image after it gets uploaded to the browser. I'm new to javascript any help I would be grateful!

file.js:

const fileSelect = document.getElementById("fileSelect"),
    fileElem = document.getElementById("fileElem"),
    fileList = document.getElementById("fileList");

fileSelect.addEventListener("click", function (e) {
    if (fileElem) {
        fileElem.click();
    }
    e.preventDefault(); // prevent navigation to "#"
}, false);

fileElem.addEventListener("change", handleFiles, false);

function handleFiles() {
    if (!this.files.length) {
        fileList.innerHTML = "<p>No files selected!</p>";
    } else {
        fileList.innerHTML = "";
        const list = document.createElement("ul");
        fileList.appendChild(list);
        for (let i = 0; i < this.files.length; i++) {
            const li = document.createElement("li");
            list.appendChild(li);

            const img = document.createElement("img");
            img.src = URL.createObjectURL(this.files[i]);
            img.height = 60;
            img.onload = function () {
                URL.revokeObjectURL(this.src);
            }
            li.appendChild(img);
            
        }
    }
}

html file:

<body>
        <input type="file" id="fileElem" multiple accept="image/*" style="display:none">
        <a href="#" id="fileSelect">Select some files</a>
        <div id="fileList">
            <p>No files selected!</p>
        </div>
       

        <!-- ************** js ********** -->
        <script src="./file.js" type="text/javascript"></script>
    </body>
  • 1
    I think the better way is resize/crop images on server side with php ([example](https://www.php.net/manual/ru/function.imagecopyresized.php)) or something. But for js there you can try to use some libraryies [Cropper.js](https://fengyuanchen.github.io/cropperjs/) or [native js example](https://stackoverflow.com/a/43550946/14135825) [Native example 2](https://www.therogerlab.com/how-can-i/javascript/resize-an-image.html) – Greg-- Aug 21 '20 at 12:13
  • thanks man! appreciated – Abdalla Abdalmunim Aug 21 '20 at 12:38

0 Answers0