Friday, October 24, 2008

Learn how to resize image with JavaScript

In this post you'll learn how to resize any image with simple JavaScript.

To resize the images, you need to first create a javascript function to do the resizing. Feel free to use this one that I wrote:

function resize(which, max) {
var elem = document.getElementById(which);
if (elem == undefined || elem == null) return false;
if (max == undefined) max = 100;
if (elem.width > elem.height) {
if (elem.width > max) elem.width = max;
} else {
if (elem.height > max) elem.height = max;
}
}


This function has been tested successfully against IE 6 & 7 and Firefox 2 & 3. One thing worth mentioning is that only the longest side of the image needs to be resized to fit your maximum size. The aspect ratio will still be maintained by the web browser.

The resize function expects an image id and an optional maximum size. For this to work properly, the resizing must only occur after the image was loaded. This can be enforced by using the onload attribute of the image tag.

So, in pure HTML, this could be called like so:

<img id="any_image" onload="resize('any_image')" src="any_image.jpg" />


Download Free Image Cropper Tool

Enjoy!

Related Posts :





0 comments :

Post a Comment

 

Copyright © 2009 - tutorialfeed.org