How can I proportionally scale down an <img> element with the shorter of its WxH set to a fixed number?


<div id="thumbnail">
  <img src="xxx">


border: 2px solid #ccc;
width: 50px;
height: 50px;
overflow: hidden;

Say the image size is greater than 50x50, is there any way that I can proportionally scale down the image so that the shorter of its width and height would become 50px? Note that the image can be in either portrait or landscape.


First load up the image in javascript to get its real dimensions.

var img = new Image('image.jpg');
var width = img.width;
var height = img.height;

Then determine which one has the larger height, and adjust them accordingly using the ratios.

if (width <= height) {
    var ratio = width/height;
    var newWidth = 50;
    var newHeight = 50 * ratio;
} else {
    var ratio = height/width;
    var newWidth = 50 * ratio;
    var newHeight = 50;

Then insert the image into the DOM using jQuery.

$('#imageContainer').append('<img src="' + img.src + '" style="width:' + newWidth + 'px; height:' + newHeight + 'px;" />');

Divide the width of the image by the height, that's your ratio. Then find what's the largest dimension, if it's the width, set the width = 50 * ratio, and height = 50; if it's the height set it height = 50 / ratio and the width = 50. Do you need Javascript code?

Need Your Help

Problem passing NSError back as a return parameter

iphone objective-c nserror

I am having a problem passing an NSError object back. The first line of code to access the object (in this case, I inserted an NSLog) causes "EXC_BAD_ACCESS".

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.