JavaScript simple image resizer

Often one needs to resize images only using client-side programming. For cases like that, I’m using a technique with JavaScript. Depending on the original size and the desired final size, it may distort a little or lose quality. But in most cases, it’s still useful.

The image is resized proportionately and limited to the maximum size set in the variables maxHeight and maxWidth.

function resizeImage(img) {

  // Maximum dimensions.
  var maxWidth = 300;
  var maxHeight = 100;

  // The ratio between the wanted width and height.
  var ratio = img.clientWidth / img.clientHeight;

  if (maxWidth / maxHeight > ratio) {
    img.width = maxHeight * ratio;
    img.height = maxHeight;
  } else {
    img.height = maxWidth / ratio;
    img.width = maxWidth;

Using the function

With native JavaScript:

var img = document.getElementById('myimagem');

With jQuery:

$('img.resize').each(function () {

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

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