Resize Images with Javascript
May 30th, 2006
If you need to force images to fit within your web page layout you really only have two options:
- Resize images on the server.
- Resize images on the client.
Resize images on the server
If you have the resources, resizing on the server is probably the best solution depending on your requirements. This solution requires server-side software to manipulate the images and store the altered image for future reference. For Ruby, the RMagick library does an excellent job with this. However, manipulating images on the server is a very expensive operation. If you are on a shared server, like I am, this may not be an option for you. But don’t worry, there is an alternative below.
Resize images on the client
The other option for resizing images involves using Javascript on the client-side to resize them on the fly. This solution has two drawbacks:
- It requires Javascript.
- It requires downloading the full image, whereas the server-side resizing will result in much smaller image sizes.
If these two drawbacks are ok with you, then read on :)
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 and Firefox 1.5 (if you can verify this against others, please let me know and I will update this list). 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="some_image" onload="resize('some_image')" src="some_image.jpg" />
And in Ruby on Rails, this would look like:
<%= image_tag('some_image.jpg', {:id => “some_image”, :onload => “resize(’some_image’)”}) %>
Enjoy!
Subscribe to the feed!
April 14th, 2007 at 9:11 am
this function does not preserve aspectratio whatsoever
April 14th, 2007 at 1:15 pm
Re: this function does not preserve aspectratio whatsoever
I did verify that this maintains the aspect ratio for FireFox 1.5 and Internet Explorer 6. If you let me know what browser are you using I will see if I can verify or at least update this post with a NOTE. The alternative is of course to just compute the explicit width and height yourself. I have done this in the past so if you need help just let me konw.
May 10th, 2007 at 8:55 am
[…] Re: PHP code needed JavaScript, not Java. They are two unrelated, different things. I don’t use JavaScript because I don’t like it. However, a quick Google search yielded these results: Dynamically Resizing Images - WebReference.com atom thoughts
June 20th, 2007 at 12:43 pm
Or you could just us css to resize your images - seems like a much simpler solution.
June 20th, 2007 at 12:47 pm
Hi Max,
I could be mistaken but won’t that just reduce the visible area of the image? With the Javascript approach, it will actually dynamically shrink the image to the new dimensions.
Tom
July 30th, 2007 at 5:46 pm
Well Tom..
Yes - you are absolutely right on that one. But I don’t see much difference between resizing the actual image using javascript, and just applying some simple CSS to deal with the problem. Not from a user perspective anyway.
Max
February 20th, 2008 at 3:25 pm
Is there a way to get an image to resize when I click a thumbnail of it, to enlarge the image next to a list of thumbnails. I want the size of the enlarged image to be different than the images actual size though. I can get the images full size to appear, but not a smaller size.
i.e. I click a thumbnail and the 1588×2080 image shows up and not a 300×400.
This is my part of code I’m stuck on. The height and width properties I have are doing nothing.
Thanks
Scott
February 20th, 2008 at 3:26 pm
For some reason the code didn’t show up. Here it is:
February 20th, 2008 at 3:27 pm
February 20th, 2008 at 3:28 pm
sorry I can not seem to figure out how to put in my code
div id=”loadarea” style=”width: 400px; height: 300px”>/div>
April 15th, 2008 at 2:36 am
good code keep it up
May 15th, 2008 at 2:57 am
Hi, Tom
As part of your code, image resize is working fine
in this link
http://www.eklog.com/naveen.html
when ever i click sign up button the new page will be opened, that is http://www.eklog.com/mainpage_calendar/signup.aspx?n=&m=
upto fine,
in this page if i click the home button, the link is passing to the fallowing link http://www.eklog.com/naveen.html
but images or not resized when i click the home page link, this is working fine in firefox 2.0 but not internet explorer 6.0 and above. how to resolve this problem, this is very urgent for me, please give me a solution.
Naveen Reddy
June 5th, 2008 at 9:35 am
If you need to change the image keeping its proportions replace the resize code with this:
function thumb_resize(which, max) {
var elem = document.getElementById(which);
if (elem == undefined || elem == null) return false;
var orig_width = elem.width;
var orig_height = elem.height;
if (max == undefined) max = 150;
if (elem.width > elem.height) {
if (elem.width > max) { elem.width = max; elem.height = orig_height*(max/orig_width);}
} else {
if (elem.height > max) { elem.height = max; elem.width = orig_width*(max/orig_height);};
}
}
June 6th, 2008 at 6:06 am
hi,
Thanassis,
as part of your suggestion i tried with your code, its not given any solution what ever i mentioned in previous links, when ever i click the browser back button(after click in any link) my images are not resized , please check the once again.
the link is http://www.eklog.com/naveen.html
thanking you
naveen reddy
August 18th, 2008 at 5:30 pm
This code works fine for preserving aspect ratio.
The CSS obviously wont work if the aspect ratio is anything but whatever those pixels work out to.
I changed the code up a bit to pass in ‘this’ instead of the id, this lets me remove that first line and remove the id from the element.
I also removed the inner if statements to also increase the size of the image to fill the invisible square.
(Tested in IE7)
-Charlie
August 18th, 2008 at 9:17 pm
@Charlie: Great! Thanks for the feedback. Glad this was useful to you. Your improvements sound good. Less lines for the same functionality is always better :)
December 24th, 2008 at 9:16 am
I am using a class .thumbnail that resizes the larger image to a thumbnail. My problem is that there are portrait and there are landscape images. You cannot do that with CSS unless you write a lot of code. I want to implement a script that will resize the image to a thumbnail based on its width or based on its height seperate from each other so that when the user clicks on the resized thumbnail the image returns to it’s origional file size in another divider. If I set the images to a certain width and a certain height when saving them then I run the risk of distorting the image and I cannot do that since the website i am working on is for a photographer. I think that using CSS to resize the image makes it easy with the percentage (width:40%) and it works great, however, who wants to code each photo with either (class=”portrait”) or (class=”landscape”) if the percentage can be used with script to do the comparison and then resize the image to a thumbnail? We are talking hundreds of images…
January 18th, 2009 at 10:56 am
Re:last post,
Thanks Tom for this code, as you can see, i am new to javascript. This works great for me in Firefox 3.0.5
and IE beta version 8.0!
(not alot of code, because i have a life too!)
Eyveneena
January 18th, 2009 at 10:58 am
Re: last post,
It also works great in Google Chrome…
Eyveneena
May 24th, 2009 at 6:43 pm
Nice Solution for a links resizing :D THanks
June 10th, 2009 at 9:16 am
I didn’t know that only the longest side of the image needs to be resized. I kept wondering why with my browser scaled down one side even more. After reading this, I fixed my script and it works perfectly in IE and Firefox. Thanks Tom
July 27th, 2009 at 5:52 am
did not work for me until i specified a width and a height for the image in the html IMG tag. instead of this script, anyway, i just used
this.width=100; this.height=100;
written in the HTML tag onmouseover
August 4th, 2009 at 9:31 am
Hello..if you need scale to some the image to some div
preview:function(img){
var tpl = ‘’;
if(this.pathImages) var path = this.pathImages;
if(this.wo) var path = this.wo.Browser.pathImages;
if(!img && this.selectedFile)
img = this.selectedFile;
if(!img) return;
var ie =navigator.userAgent.match(/MSIE\s([^;]*)/);
var noCache = ie ? ‘?t=’+Math.round(new Date().getTime()/1000):'’;
var preview = new Image();
preview.src = ‘/’+path+img+noCache;
preview.onload = function(){
// var width = Number(this.width);
// var height = Number(this.height);
var toWidth = document.getElementById(’preview’).clientWidth;
var toHeight = document.getElementById(’preview’).clientHeight;
// debugger;
if (preview.width > preview.height) {
if (preview.width > toWidth) {
newWidth = toWidth;
newHeight = preview.height*(toWidth/preview.width);
}
} else {
if (preview.height > toHeight) {
newHeight = toHeight;
newWidth = preview.width*(toHeight/preview.height);
}
}
tpl = ‘’;
document.getElementById(’preview’).innerHTML=tpl;
}
},
August 10th, 2009 at 3:24 am
super awesome Tom, i am fascinated by the simplicity of this :), after spending a quite a while googling for the solution.
all i needed was a way to squeeze a big image into a container. Meanwhile, you can safely add Safari 4 to the list of browsers this works in.
thankss!!