Resize and Center image with jQuery

Looks like I haven’t explained myself well. I do apologize for that.

I have edited this question to make it more clear.

The scenario

We have a website that doesn’t host the images. What it does is a reference to an image in other server.

The plan

  • Resize images keeping proportions.
  • Center resized images.
  • Flexible so it can fit in several sizes.

The bug

My code works as intended, however there is a Bug that only happens sometimes.

If you go to the search page of the website, and swap between page 1, 2, 3 and 4 a couple of times, you will notice that sometimes the images are good… other times they appear aligned left, and do not take up the full container area.

The links

The full website (in beta)

The JavaScript File

The jQuery plugin that helped me (jThumb)

The plan (detailed version)

Let’s say that the image is 600x400 pixels (remember they are not hosted on this server), and with jQuery and CSS, I want to resize the image (keeping proportions) in to a container of 310x200 pixels.

The other challenge is to center the image.

All this has to be flexible because there are several different containers sizes in the website.

What I have done so far (you can find this in the link above)

To resize the image I'm doing:

var img = new Image();
img.src = $(this).attr("src");
var width = $(this).css('width');
var height = $(this).css('height');

var photoAspectRatio = img.width / img.height;
var canvasAspectRatio = width.replace("px", "") / height.replace("px", "");

if (photoAspectRatio < canvasAspectRatio) {
    $(this).css('width', width);
    $(this).css('height', 'auto');

    var intHeight = height.replace("px", ""); //tirar o PX
    $(this).css('marginTop', (-Math.floor(intHeight / 2)));
else {
    $(this).css('width', 'auto');
    $(this).css('height', height);

$(this).wrap('<div class="thumb-img" style="width:' + width + ' ;height:' + height + ';"><div class="thumb-inner">' + '</div></div>');

To center the image I’m doing:

jQuery(this).left( '-' + ( parseInt( $(this).width() ) / 2 ) + 'px' );
jQuery(this).top( '-' + ( parseInt( $(this).height() ) / 2 ) + 'px' );
jQuery(this).css('margin-left', '50%' );
jQuery(this).css('margin-top', '50%');

There's a far simpler solution to determine how to resize and position the image. It will work with all image and container sizes.

var canvasWidth = parseInt(width);
var canvasHeight = parseInt(height);

var minRatio = Math.min(canvasWidth / img.width, canvasHeight / img.height);
var newImgWidth = minRatio * img.width;
var newImgHeight = minRatio * img.height;

var newImgX = (canvasWidth - newImgWidth) / 2;
var newImgY = (canvasHeight - newImgHeight) / 2;

Now just position the image using newImgX, newImgY, and resize it to newImgWidth, newImageHeight.

This is probably a race condition. You are setting the img src and then immediately trying to get its width and height attributes. But there is no guarantee that the web browser has downloaded the image or pulled it from the browser cache yet, and if it hasn't, your code will lead to unexpected results.

You need to do something like this:

var img = new Image();
var $thumb = $(this);

img.load(function() {
  /* .....[image calculation and resize logic]..... */

img.src = $thumb.attr("src");

Note that the order of the above statements is very important -- you must attach the img.load event handler first, then assign the img.src second. If you do it in the other order, you will end up with an opposite race condition (the image may already be loaded after the img.src assignment, in which case the event handler will not be called in all browsers -- by setting the event handler first you ensure that it will be called after the img.src assignment even if the image is already loaded).

Also, note the $thumb definition at the top. This is because "this", inside the img.load function, will be a reference to the new "img", not the thumbnail element. So your logic will have to reference "$thumb" for the DOM element and "this" (or "img") for the in-memory image.

Also, for the actual logic take a look at the answer "Scott S" provided above. His suggestion looks simpler than what you have.

It's not clear from your question, but I'm assuming one your issues is the left-align of the images in the table at the bottom half of your front page at

The issue here is not your jQuery code, rather it is your CSS.

add a text-align: center to your thumb-inner class. Then make sure that rule is loaded AFTER the "table.dlRandom img, ..." rule - or remove the display:block from that rule. That should center those images.

Generally though - to scale the image, your logic looks correct up to the point of the div. Don't quite understand that logic. You don't need to set the auto size though, just restrain the dimension that is required.

One tangential tip - in the code above you reference $(this) no less than 16 times. Do this at the top of the function, and use it from there on:

var $this = $(this);

I really didn't get your question but this maybe be help you.

function resizer(imgCls, maxWidth, maxHeight) {
    var img = $('img'), imgWidth, imgHeight;
    img.each(function () {
        imgWidth = this.width;
        imgHeight = this.height;
        if (imgWidth > maxWidth || imgHeight > maxHeight) {
            var widthFact = maxWidth / imgWidth;
            var heightFact = maxHeight / imgHeight;
            var chooseFact = (widthFact > heightFact) ? heightFact : widthFact;
            imgWidth = imgWidth * chooseFact;
            imgHeight = imgHeight * chooseFact;

this code gets the images matches the provided className and looks your arguments. pass maxWidth to your maxWidth value such as 300 px, and pass maxHeight to your images maxHeight such as 300.

then the function will loop for every image and checks its width and height. If its width or height is larger than your max values then it will be resized by keeping the aspect ratio.

Please let you free to ask more question about the issue and please be more clear.

This script will shrinks, and align image depending of their orientation. Image is rounded with div ho has fixed width and hight, and also a style set to overflow:hidden. The script actual recognize the image orientation and ad to image a margin-left or margin-top in minus atribute to style depending of a image vertical or horizontal orientation.


<style type="text/css">
.thumb {

jquery with javascript:

window.onload = function() {
  var images = $(".image_center");
  for(i=0; i<images.length; i++)
     images[i].onload = centerImage(images[i]);

  function centerImage(img) {
   if (img.width > img.height ) {
   var y = 160;
   var x = img.width/img.height*y;
   var marx = (x-y)/2; = y+"px"; = -(marx) + "px";
   if (img.width < img.height ) {
   var x = 160;
   var y = img.height/img.width*x;
   var mary = (y-x)/2; = x+"px"; = -(mary) + "px";


<div class="thumb"><img class="image_center" src="sa.jpg" alt="#" /></div>
<div class="thumb"><img class="image_center" src="sb.jpg" alt="#" /></div>

You can see demo here: Link

Another useful plugin which achieves this is jQuery Center Image which supports two modes. One to fill the entire space by cropping and resizing the image and another which emulates max-width/max-height to resize to fit within the space.