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');
resizeImage(img);

With jQuery:

$('img.resize').each(function () {
  resizeImage(this);
});
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s