Robert Tamayo


Resizing an Image in a Web App Before Uploading to Server

I once made a web app that let users upload images of locations to share with each other. The problem with it was that pictures taken by phones are so tremendously large nowadays. The large filesize of the image presented the following problems:

  • Phone screens are small. For an app that would display images on a CSS pixel size of 480, images don't need to be 7 thousand pixels wide.
  • Phones have slower connection speeds. Image file sizes in the order of megabytes would not make for a fast download/upload speed. The upload speeds would be even slower, and that would make users not willing to upload images due to the slowness of the app.
  • Larges files take up more space on the server. Finally, there was the issue of server storage space; one thousand 1MB files would be 1GB, whereas if I could make them 10KB I could store 100,000 images per gigabyte.

The Solution

The solution will follow some basic steps:

  1. Create a form that accepts an image as the input
  2. Create a placeholder canvas element
  3. When an image is set by the form, copy its data to the canvas element.
  4. Resize the canvas to the desired pixel range, painting the image onto it.
  5. Change the form's data to the resized image created by the canvas

The Form Element

The Compress Function

compress() {
        let formImage = document.getElementById('image_file[]');
        const fileName = formImage.files[0].name;
        const reader = new FileReader();
        reader.onload = event => {

The key here is the FileReader's readAsDataURL function. Instead of reading an actual file, we can read the image data and use that as the reader url. To start manipulating the data in the reader, we have to wait for the reader to finish loading the image url.

Leave a Comment