Languages
[Edit]
EN

JavaScript - resize JPG image (Vanilla JS)

4 points
Created by:
starcraf35
754

In this article, we would like to show how to resize or reduce image size in pure JavaScript using canvas.

Image resize concept using JavaScript (Vanilla JS).
Image resize concept using JavaScript (Vanilla JS).

Practical example:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <img id="dst-image">
  <script>

    function resizeImage$1(imageElement, newWidth, newHeight, newQuality) {
        var canvas = document.createElement('canvas');
        canvas.width = newWidth;
        canvas.height = newHeight;
        var context = canvas.getContext('2d');
        context.drawImage(imageElement, 0, 0, newWidth, newHeight);
        try {
            return canvas.toDataURL('image/jpeg', newQuality);
        } catch (e) {
            return null;
        }
    };

    function resizeImage$2(imageUrl, newWidth, newHeight, newQuality, onReady, onError) {
        var image = document.createElement('img');
      	image.onload = function() {
        	var dataUrl = resizeImage$1(image, newWidth, newHeight, newQuality);
          	if (dataUrl) {
                onReady(dataUrl);
            } else {
                if (onError) {
                    onError('Image saving error.');
                }
            }
        };
        image.onerror = function() {
            if (onError) {
                onError('Image loading error.');
            }
        };
      	image.src = imageUrl;
    };
    

    // Usage example:

    var srcUrl = 'https://dirask.com/static/bucket/1655940866050-LbA292PD9v--original-image.jpg';
    
    var newWidth = 300;
    var newHeight = 300;
    var newQuality = 0.9;  // should be from 0 to 1.0

    function onReady(dataUrl) {
    	var dstImage = document.querySelector('#dst-image');
    	dstImage.src = dataUrl;
    }
    function onError(message) {
    	console.error(message);
    }
    
    resizeImage$2(srcUrl, newWidth, newHeight, newQuality, onReady, onError);

  </script>
</body>
</html>

 

Used resource:

 

Alternative titles

  1. JavaScript - reduce JPG image size (Vanilla JS)
  2. JavaScript - reduce JPG image size using canvas (Vanilla JS)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join