Oz Web Services
  • Home
  • WP
  • PHP
  • JS
  • CSS
  • SCSS
  • HTML
  • XML
  • JSON
  • SQL
  • .htaccess
  • Apache
  • Nginx
  • INI
  • HTTP
  • Diff
Search shortcode

jQuery: Resize Images Proportionally

May 25, 2014
Original: http://stackoverflow.com/questions/3971841/how-to-resize-images-proportionally-keeping-the-aspect-ratio
// TODO: rework this
$('.container img').each(function() {
	var maxWidth  = 100,               // Max width for the image
		maxHeight = 100,               // Max height for the image
		ratio     = 0,                 // Used for aspect ratio
		w     = $(this).width(),        // Current image width
		h    = $(this).height();      // Current image height

	// Check if the current width is larger than the max
	if(width > maxWidth){
		ratio = maxWidth / width;               // get ratio for scaling image
		$(this).css("width", maxWidth);         // Set new width
		$(this).css("height", height * ratio);  // Scale height based on ratio
		h = h * ratio;                     // Reset height to match scaled image
		w = w * ratio;                      // Reset width to match scaled image
	}

	// Check if current height is larger than max
	if(height > maxHeight){
		ratio = maxHeight / height;           // get ratio for scaling image
		$(this).css("height", maxHeight);     // Set new height
		$(this).css("width", width * ratio);  // Scale width based on ratio
		w = w * ratio;                    // Reset width to match scaled image
		h = h * ratio;                  // Reset height to match scaled image
	}
});

$('.container img').each(function() {
	var mw = 100,               // Max width
		mh = 100,               // Max height
		r  = 1,                 // Aspect ratio
		w  = $(this).width(),   // Current width
		h  = $(this).height();  // Current height

	// set ratio
	r = w > mw ? mw/w : mh/h;

	// Check if current width is larger than the max
	if( w > mw ){
		// r = maxWidth / width;       // get ratio for scaling image
		$(this).css("width", mw);      // Set new width
		$(this).css("height", h * r);  // Scale height based on ratio
	}

	// Check if current height is larger than max
	if( h > mh ){
		// r = maxHeight / height;    // get ratio for scaling image
		$(this).css("width", w * r);  // Scale width based on ratio
		$(this).css("height", mh);    // Set new height
	}

	w = w * ratio;  // Reset width to match scaled image
	h = h * ratio;  // Reset height to match scaled image
});
Oz Web Services
Copyright © 2015-2025 All Rights Reserved