Keeping aspect ratio when scaling an image

Scaling an image to keep it under specific bounds, for visualizing purposes is a common task, but it’s even better if we can scale the image without deforming it. In this cases we have to scale the image and keep it’s original aspect ratio.

Nowadays there are thousands of libraries for any general purpose language that can perform the scaling of an image. The question is ¿which are the new width and height for the image?

Following there is this simple code, that have been tested using javascript, but should work in PHP, Python, Java, Perl, C, or whatever language you want to try :)

if (w < h) {
  h = (h * maxWidth) / w;
  w = maxWidth;
}
else {
  w = (w * maxHeight) / h;
  h = maxHeight;
}

w represents the image width

h represents the image height

maxWidth represents the maximum width boundary where the image is going to be embedded

maxHeight represents the maximum height boundary where the image is going to be embedded

As a final example, although is a copy-paste, imagine you have an image of size (w, h) and you have to fit it in an area of 640×480:

var maxWidth = 640, maxHeight = 480;
if (w > maxWidth || h > maxHeight) {
  if (w < h) {
    h = (h * maxWidth) / w;
    w = maxWidth;
  }
  else {
    w = (w * maxHeight) / h;
    h = maxHeight;
  }
}

Trackback URL

, , , , ,

17 Comments on "Keeping aspect ratio when scaling an image"

  1. Ivan
    27/03/2009 at 3:02 pm Permalink

    Joer Pau, ¿tu me lees la mente? (o deberia decir el mantis)

    Justo esa era una de las tareas que tenia marcadas para la proxima semana. Fijate en la foto de moda2012 que aparece debajo de la sección “ropa” (la de la chica en ropa interior). Aparece deformada justo por eso. El theme es una muy bueno en cuanto a diseño pero tiene errores garrafales en cuanto a programacion (el panel de la derecha “galeria de moda” tambien deformaba las imagenes y lo tuve que corregir de una forma muy parecida a la que explicas en el articulo pero en PHP).

    De todas formas lo mas jodido (o lento) suele ser obtener las dimensiones de una imagen arbitraria.

  2. Pau Sanchez
    28/03/2009 at 2:01 am Permalink

    Se ve que es muy común xD

    Si quieres te pongo el comando de imagemagick que te deja las fotos niqueladas. De hecho tengo una funcioncita mágica en PHP + ImageMagick que coge una imagen, la rota usando EXIF, le pone watermark (si se quiere y en la posicion que se quiera), la escala manteniendo el aspect ratio, y un par de cosas más :)

  3. Ivan
    29/03/2009 at 1:21 pm Permalink

    ImageMagick es demasiado pesado :)
    No, como yo lo uso es igual que tu pero pongo en el tag IMG el tamaño calculado y dejo que sea el browser quien haga el “trabajo sucio”. Ya sabes que DH es muy suyo con eso de usar demasiada CPU…

  4. Pau Sanchez
    29/03/2009 at 1:41 pm Permalink

    Hombre, todo depende del número de imágenes que haya que resizear al dia. Una vez una imagen queda redimensionada ya no hay que tocarla, gastará menos ancho de banda.

    De todos modos comprendo el tema de DreamHost, y si crees que vale la pena que se haga desde el cliente, no creo que te equivoques.

Hi Stranger, leave a comment:

ALLOWED XHTML TAGS:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

Subscribe to Comments