Showing posts with label javascript code. Show all posts
Showing posts with label javascript code. Show all posts

Monday, April 20, 2026

Image Compressor (JavaScript)


 

<input type="file" id="upload" accept="image/*">

<br><br>

<img id="preview" style="max-width:300px;"><br><br>

<a id="download" download="compressed.jpg">Download Compressed Image</a>



<script>

document.getElementById("upload").addEventListener("change", function(e) {

    const file = e.target.files[0];



    if (!file) return;



    const reader = new FileReader();



    reader.onload = function(event) {

        const img = new Image();



        img.onload = function() {

            const canvas = document.createElement("canvas");

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



            // 🔹 Resize (optional)

            const maxWidth = 800;

            const scale = maxWidth / img.width;



            canvas.width = maxWidth;

            canvas.height = img.height * scale;



            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);



            // 🔹 Compress (0.0 - 1.0)

            const quality = 0.6;



            const compressedData = canvas.toDataURL("image/jpeg", quality);



            // Preview

            document.getElementById("preview").src = compressedData;



            // Download link

            document.getElementById("download").href = compressedData;

        };



        img.src = event.target.result;

    };



    reader.readAsDataURL(file);

});

</script>

Image Compressor (JavaScript)

  <input type = "file" id = "upload" accept = "image/*" > <br><br> <img id = "pr...