Hi,
found and good
CSS + Javascript solution to dynamically resize images while maintaining aspect ratio
Saturday, 12 Dec 2009
I couldn’t find a good script for creating thumbnails with CSS + Javascript, so I wrote one. The objective is to:
1. Center the images.
2. Resize the images to a predefined thumbnail width and height.
3. Do this on the fly to avoid server-side rendering of thumbnails.
You can check out a demo of this script live on this site in the photos section. Or live on Fotomoto’s homepage.
First, the CSS required. You can alter the width and height to the desired width and height of your thumbnails.
.image_outer {
overflow:hidden;
border:1px solid #dedede;
}
.image_inner {
padding:0px;
margin:0px;
position:relative;
overflow:hidden;
}
.image_outer .image_inner img {
border:0px;
}
Second, the XHTML markup looks something like this:
<div class="image_outer">
<div class="image_inner">
<img class="resizeMe" src="someUrl" alt="my image" />
</div>
</div>
The logic for this set-up: 1. The image sits inside a relatively positioned container (.image_inner). The container is set (by Javascript) to a set width / height, which is the thumbnail size. 2. The relatively positioned container sits inside an outer container (.image_outer) that prevents the inner container from losing its position in the vertical layout of the page.
The javascript to render the images is simple. Here’s sample code using jQuery:
function resizeImages(classToResize,w,h) {
var imgs = $("."+classToResize);
jQuery.each(imgs, function() {
// set container dimensions
$(this).parent().parent().height(h);
$(this).parent().parent().width(w);
$(this).parent().height(h);
$(this).parent().width(w);
// get current image dimensions
var cur_h = imgs[i].height;
var cur_w = imgs[i].width;
// is aspect ratio wider or taller than the thumbnail box?
if ((cur_h/cur_w)>(h/w)) {
$(this).width(w);
var diff = (imgs[i].height - h)/2;
$(this).parent().parent().scrollTop(diff);
} else {
$(this).height(h);
var diff = (imgs[i].width - w)/2;
$(this).parent().parent().scrollLeft(diff);
}
}
}
The script broken down step-by-step:
1. Query the images by the class name.
2. The for loop iterates through all of the images.
3. The resize logic is based on the aspect-ratio of the images. If the aspect ratio of the original image is greater than the desired thumbnail size, the scroll position of the container is set accordingly to center the image and the image’s width is set to the desired thumbnail size. Alternately, if the aspect ratio is equal to or less than the original image, the scroll position and image height are set accordingly to center the image.
Note: This function should be called onLoad to ensure that all images are loaded when the script executes; this can be done in jQuery using a construction like $(document).ready(function() { resizeImages(‘resizeMe’,300,200); });