Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
           CodeHim.com

Free Web Design Code & Scripts

       
  • Home
  • Code Snippets
    • Accordion
    • Creative
    • Carousel
    • Date & Time
    • Gallery
    • LightBox
    • Menu & Nav
    • Modal
    • Others
    • Portfolio
    • Social Media
    • Text & Input
    • Video Player
    • Zoom
  • HTML & CSS
  • Bootstrap
  • JavaScript
  • Collections
  • About
  • Contact
  • Buy Me a Coffee

Home / Vanilla JavaScript / JavaScript Compress Image Before Upload

JavaScript Compress Image Before Upload

January 22, 2024January 19, 2024 by Asif Mughal
JavaScript Compress Image Before Upload
Share This:
Code Snippet:Frontend Image Compress
Author: dylandy.chang
Published: January 19, 2024
Last Updated: January 22, 2024
Downloads: 1,432
License: MIT
Edit Code online: View on CodePen
Read More
 Demo
Download (File path is not allowed!)

This JavaScript code helps you to compress image size before upload to server. It calculates and displays the original image size in MB when you choose an image. Then, it displays the image, compresses it into WebP format, and reveals the new compressed size in KB. This code is handy for making your web pages load faster by reducing image sizes before uploading them.

How to Compress Image Size Before Upload using JavaScript

1. Include the following HTML structure in your webpage. This code assumes you have an input field for selecting an image, a display area for the image before compression, and a display area for the image after compression.

<input type="file" name="upload-image" id="upload-image" required />
<h2> Before </h2>
<p name="before-compression"></p>
<img src="" class="before" style="display:none;"/>
<canvas style="display: none;"></canvas>
<h2> After </h2>
<p name="after-compression"></p>
<img src="" class="after" style="display:none;"/>

2. You can customize the CSS styles to match your website’s design, but the following code includes basic styling for the elements. Adjust it as needed.

#upload-image{
   display: block;
}
.before, .after{
  max-width: 640px;
}

3. Copy and paste the JavaScript code into your webpage. This code handles the image compression process.

const ReadAndCompress = (e) => {
  const size = `Before Compression: ${(e.target.files[0].size/(1000*1024)).toFixed(2)} MB`;
  document.querySelector("p[name=before-compression]").innerHTML = size;
  const reader = new FileReader();
  reader.readAsDataURL(e.target.files[0]);

  reader.onload = event => {
    const img = document.querySelector("img.before");
    img.src = event.target.result;
    img.style = "display: block";
    img.onload = () => {
      const width = img.width;
      const height = img.height;
      const elem = document.querySelector('canvas');
      elem.width = width;
      elem.height = height;
      const ctx = elem.getContext('2d');
      ctx.drawImage(img, 0, 0, width, height);
      const webp = ctx.canvas.toDataURL("image/webp", 0.5);
      const imgAfter = document.querySelector("img.after");
      imgAfter.src = webp;
      imgAfter.style = "display: block";
      const head = 'data:image/webp;base64,';
      const imgFileSize = (Math.round((webp.length - head.length)*3/4) / (1000)).toFixed(2);
      document.querySelector("p[name=after-compression]").innerHTML =
        `After Compression: ${imgFileSize} KB`;
    },
    reader.onerror = error => console.error(error);
  }
}

document.querySelector("input[name=upload-image]")
.addEventListener("change", (event) => ReadAndCompress(event))

4. To upload the compressed image that is shown as output, you can modify the provided code by adding a function to send the compressed image to your server or a cloud storage service. Here’s a general outline of how you can do it:

<input type="file" name="upload-compressed-image" id="upload-compressed-image" required />
<button id="upload-button">Upload Compressed Image</button>

5. Add an event listener to the new upload button or form to trigger the upload process. You can use the Fetch API or any other method to send the compressed image to your server.

document.querySelector("#upload-button").addEventListener("click", () => {
const compressedImage = document.querySelector("img.after").src;
uploadCompressedImage(compressedImage);
});

function uploadCompressedImage(compressedImage) {
// Use the Fetch API or another method to send 'compressedImage' to your server.
// You may need to handle server-side processing and storage of the uploaded image.
}

Remember that the server-side handling part will depend on your backend technology stack. The code provided here outlines the client-side modifications to initiate the upload process.

That’s all! hopefully, you have successfully created a feature to compress Image size Before Upload. If you have any questions or suggestions, feel free to comment below.

Similar Code Snippets:

  • Automatic Logout After 15 Minutes Of Inactivity in JavaScript

    Automatic Logout After 15 Minutes Of Inactivity in JavaScript

  • Vanilla JavaScript Tag Input with CSS

    Vanilla JavaScript Tag Input with CSS

  • JavaScript Element Resize Event

    JavaScript Element Resize Event

  • Drag and Drop Task List in JavaScript

    Drag and Drop Task List in JavaScript

  • JavaScript Image Viewer with Zoom Pan Rotate and Flip

    JavaScript Image Viewer with Zoom Pan Rotate and Flip

  • JavaScript Draggable Sorting Tags

    JavaScript Draggable Sorting Tags

  • Progressive Image Loading in JavaScript

    Progressive Image Loading in JavaScript

  • Pure JavaScript Lightbox - Vanilla JS Image Lightbox

    Pure JavaScript Lightbox - Vanilla JS Image Lightbox

  • Movie Ticket Booking Using JavaScript

    Movie Ticket Booking Using JavaScript

Asif Mughal

I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.

Categories Vanilla JavaScript
jQuery Select all Checkboxes in Table Column
CSS Loading Progress Bar Animation

Leave a Comment Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  • Categories

    • Accordion 22
    • Bootstrap 81
      • Bootstrap Accordion 1
      • Bootstrap Buttons 4
      • Bootstrap Cards 2
      • Bootstrap Carousel 2
      • Bootstrap Dropdowns 2
      • Bootstrap Forms 6
      • Bootstrap Jumbotron 1
      • Bootstrap Modals 2
      • Bootstrap Navbars 6
      • Bootstrap Panels 1
      • Bootstrap Progress Bars 1
      • Bootstrap Text & Input 3
    • Carousel 58
    • Chart & Graph 15
    • Date & Time 49
    • Gallery 39
    • HTML5 & CSS3 201
    • Layout 17
    • LightBox 19
    • Menu & Nav 95
    • Modal 18
    • Others 58
    • Portfolio 8
    • Social Media 10
    • Text & Input 120
    • Vanilla JavaScript 163
    • Zoom 12

You May Like

Alert (7) Analog Clock (4) Analog Clocks (5) Back to Top (4) Calculator (16) Calendar (5) Chart (3) Color Picker (4) Contact Us Forms (5) Countdown Timer (6) Datepicker (9) Digital Clocks (10) Drag and Drop (4) Dropdown Menu (23) File Uploader (4) Hamburger Menu (9) Horizontal Menu (24) Hover Effects (5) HTML5 Canvas (8) Image Sliders (40) Mega Menu (11) Modal (5) Multi-Level Menu (9) News Ticker (4) Notification (9) Off-Canvas Menu (10) Pagination (5) Parallax (8) Popup Lightbox (20) Progress Bar (5) Range Sliders (4) Scrolling Effects (28) Search Box (4) Select Dropdown (4) Shopping Cart (3) Side Menu (16) Slideshow (19) Social Share Buttons (3) Tabs (9) Text (11) Timeline (5) Timer (4) Tooltip (4) Typing Effect (6) Vertical Menu (14)

Latest Code Snippets

  • Common Open Source Security Vulnerabilities and How to Mitigate ThemCommon Open Source Security Vulnerabilities and How to Mitigate Them
    October 12, 2024
  • Animating Grid-column on Hover Using CSSAnimating Grid-column on Hover Using CSS
    April 1, 2024
  • Star Trails Animation On Mousemove in JavaScriptStar Trails Animation On Mousemove in JavaScript
    March 31, 2024
  • Gravity Button Using Pure CSSGravity Button Using Pure CSS
    March 31, 2024
  • Padlock Toggle Switch in CSSPadlock Toggle Switch in CSS
    March 31, 2024
  • Scroll-driven Animations in Pure CSSScroll-driven Animations in Pure CSS
    March 31, 2024
  • Interactive Notification Center UI in Vanilla JSInteractive Notification Center UI in Vanilla JS
    March 31, 2024
  • Emoji Spinner in Vanilla JavaScriptEmoji Spinner in Vanilla JavaScript
    March 31, 2024
  • Reveal Secret Code Using CSSReveal Secret Code Using CSS
    March 31, 2024
  • Toggle Button in CSS With Stretchable Elastic EffectToggle Button in CSS With Stretchable Elastic Effect
    March 31, 2024

Popular

  • 65+ Login Page in HTML with CSS Code Sample Simple to Difficult - 947,396 views
  • 25+ Best JavaScript Shopping Cart Examples with Demo - 211,933 views
  • Bootstrap Multiselect Dropdown with Checkboxes - 150,948 views
  • Bootstrap 5 Buttons with Icon and Text Tutorial & Demo - 112,357 views
  • 19+ Bootstrap Select Dropdown with Search Box Tutorial & Examples - 101,034 views
  • Bootstrap 5 Sidebar Menu with Submenu Collapse/Hover Tutorial Demo - 88,103 views
  • 99+ Social Media Buttons HTML Code Sample & Tutorial - 86,392 views
  • 19+ Bootstrap 5 Mega Menu Responsive/Drop Down Examples - 86,388 views
  • Bootstrap 4 Modal Popup Login Form Tutorial & Demo - 82,145 views
  • Bootstrap Vertical Menu with Submenu on Click - 80,199 views

Advertisement

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

CodeHim
  • About
  • Contact Us
  • Terms and Conditions
  • Privacy Policy
Top Categories
  • Bootstrap Snippets
  • JavaScript Snippets
  • HTML CSS Snippets
  • Menu & Nav Snippets
Get in Touch

Follow us on social media to be updated with latest web design code & scripts...

All Rights Reserved © 2026 - CodeHim Inc

Please Rel0ad/PressF5 this page if you can't click the download/preview link

F5
X