Image compression using JavaScript or JSP

As I work on creating a website similar to flickr or 500px, I've encountered an issue with the loading time of my photo-filled page. Despite resizing the images using CSS, the loading time is excessively long, taking up to 2 minutes for the page to fully load. Additionally, once loaded, the page struggles to scroll smoothly. I am on the lookout for a script that can efficiently reduce the size of the images from their current high resolution, for example, from 3000x4000 to 300x400, in order to improve performance.

Answer №1

Just a few days ago, I encountered a similar issue that I resolved.

The solution lies within the <canvas> element and its drawImage method.

Check out the following function I created. It resizes the input image to a specified width, but it can be easily modified to accept a maximum width or height, a ratio, or any other parameter.

function resizeToWidth(image, targetWidth) {
    /* Takes an HTMLImageElement as input (<img>)
     and outputs an HTMLCanvasElement (<canvas>)    */

    var originalWidth = image.naturalWidth;
    var originalHeight = image.naturalHeight;

    var targetHeight = targetWidth * (originalHeight / originalWidth);

    var interimCanvas = document.createElement('canvas');
    interimCanvas.width = originalWidth;
    interimCanvas.height = originalHeight;
    var interimCtx = interimCanvas.getContext('2d');
    var redrawnCanvas, redrawnCtx;
    var scale = 2;
    var newWidth, newHeight;

    redrawnCanvas = document.createElement('canvas');
    redrawnCanvas.width = targetWidth;
    redrawnCanvas.height = targetHeight;
    redrawnCtx = redrawnCanvas.getContext('2d');

    if (originalWidth > targetWidth) {

        /* We perform multiple passes, scaling the image by half each time.
         This approach gives a smoother result than scaling directly
         to the target size.
         The loop stops when halving once more would make the image smaller than the target size.
         */

        interimCtx.drawImage(image, 0, 0);

        do {
            redrawnCanvas = document.createElement('canvas');
            newWidth = interimCanvas.width / 2;
            newHeight = interimCanvas.height / 2;
            redrawnCanvas.width = newWidth;
            redrawnCanvas.height = newHeight;
            redrawnCtx = redrawnCanvas.getContext('2d');
            redrawnCtx.imageSmoothingEnabled = true;
            redrawnCtx.drawImage(interimCanvas, 0, 0, newWidth, newHeight);
            interimCanvas = redrawnCanvas;
            scale++;
        } while (interimCanvas.width / targetWidth > 2);
        // Final scaling to the target width
        redrawnCanvas = document.createElement('canvas');
        redrawnCanvas.width = targetWidth;
        redrawnCanvas.height = targetHeight;
        redrawnCtx = redrawnCanvas.getContext('2d');
        redrawnCtx.drawImage(interimCanvas, 0, 0, targetWidth, targetHeight);
    } else {
        redrawnCtx.drawImage(image, 0, 0, targetWidth, targetHeight);
    }

    return redrawnCanvas;
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Stop the iframe video when the modal is closed

I'm currently developing a website that incorporates the code showcased in this tutorial to launch a modal window featuring an iframe for playing YouTube or Vimeo videos. The issue arises when, as mentioned in the comments on the tutorial page, there ...

Navigating the world of getElementById and addEventListener outside of the DOM

Having some dynamic HTML code in my JS, I'm hoping to assign an ID to a particular tag: content: ` <p id="openKeyboard"> If the click happens, I want to trigger an event. </p> ` However, upon ...

Looking to transfer the name of the clicked link to a modal in order to execute a PHP/SQL query within the modal window

I am currently utilizing Twitter Bootstrap's modal feature. Within my table, I am mapping MAC addresses to vendor names using the following code: <tbody> <?php foreach ($rowarr as $k => $v) { ?> & ...

Ensuring the aspect ratio of images stays consistent within a flexbox using CSS

How can I create a grid of images without any spacing in between them? I want the width to be 100% of the parent element and each column to have the same size, for example, 20%. Using flex takes care of the columns, but I'm struggling with making the ...

I prefer showcasing the contents at the top of the page instead of the bottom

Is there a way to show the message for the $myGame variable after submitting a post? <!DOCTYPE HTML> <html> <head> </head> <body> <?php $myGame = ""; if ($_SERVER["REQUEST_METHOD"] ...

I seem to be having trouble with jQuery. Every time I try to submit my form, nothing happens

I am currently working on creating a web page for a numerical game, but I am facing difficulties with my jQuery implementation. Despite checking all my placements, nothing seems to happen when I click on the Submit button. Any assistance would be greatly a ...

Challenges with Internal Styling on Wordpress Sites

Okay. I've been dealing with some internal style issues on my Wordpress website. After dedicating hours to trying to change styles for various elements, I realized that the main html file contained a bunch of internal style sheets that were overridin ...

Why is there an issue with the JavaScript array when accessing data['sax']?

There seems to be some confusion regarding the contents of this array and how it assigns values to the variable set. It would be greatly appreciated if someone could provide an example pertaining to the usage of data['sax']. Additionally, an expl ...

What is the significance of the any type in Typescript?

As I delve into learning Typescript, a question arises in my mind. I find myself pondering the purpose of the any type. It seems redundant to specify it when every variable essentially acts as an "any" type by default. Consider this scenario where the out ...

Text Embedded in Object HTML

Feeling stuck and need some guidance. My goal is to insert text inside hexagon shapes, but I'm having trouble making it work. I can change the background-color of the hexagons, add URLs, etc., but adding text seems to be a challenge. Check out the co ...

Discovering the present width of an Angular element after it has been eliminated

Imagine you have a horizontal navigation bar coded as follows: HTML: <ul> <li ng-repeat="navItem in totalNavItems">{{name}}</li> </ul> CSS: ul, li { display: inline-block; } The data for the navigation items is fetched from thi ...

Examining whether an ajax call was not initiated within an Angular application

Is there a way to verify that an ajax request has not been made using Angular's $httpBackend? I attempted to use verifyNoOutstandingRequest() but it doesn't seem to be triggering test failures in version 1.1.5. Here is more information about the ...

The Homescreen.js file is not showing up as expected on the localhost/home page and is not displaying

Struggling to showcase the rooms on my hotel reservation website. Can't seem to crack it. Need some assistance, please. Spent a good 3 hours trying to figure this out. Snippet from My Homescreen.js import React ,{useState, useEffect, } from &apo ...

Steps to include all dependencies in an angular application

Managing a large Angular application can be challenging. I currently use npm install to install all packages and manually load them in my index.html file, like this: <script src="node_modules/angular/angular.js"></script> Similarly, I load ot ...

Placing the video at the center of the background image

                    Can someone assist me with a design issue I'm facing? I have two divs within a section. The left div contains a heading and a button, while the right div contains a video. However, when I try to add a background image to ...

dragging and dropping files for easy upload

Here is a challenge I am facing: I am looking for a solution that allows users to drag multiple images from their local file system onto the flash/flex/html5 app. The app should then extract the file name details and communicate with the server. Once t ...

A guide to smoothly transition box-shadow with jQuery's addClass() function

UPDATED I have a div with the class .shadow-circle-lg: <div class="shadow-circle-lg"></div> To add a different border styling to the div, I am using another class called .circle-highlight: .circle-highlight{ box-shadow: 0 0 0 1px rgba(0,0, ...

Utilize JavaScript to compute and implement a deeper shade of background color

To dynamically apply darker shades of background using JavaScript, I have devised the following code. .event-list .bg{ background:#eee; padding:5px; } .grid .event-list:first-child .bg{ background: #2aac97 } .grid .event-list:nth-child(2) .bg{ backgrou ...

Steps to enable navigation to external pages from a ReactJS app

I am working on a simple ReactJS application: [Demo] [Source] I am trying to implement navigation within the app from external sources without refreshing the web page. This functionality should be similar to using this.props.history.push(...). /public/i ...

Deselect an HTML checkbox using a corresponding label's "for" attribute

Below is the html code I am using to display a checkbox with an image: <div class="testClass"> <input id="111" name="compare_checkbox" type="checkbox" /> <label for="111"> <i class="icon" aria-hidden="true"&g ...