Make images square

Last modified: February 24, 2006 - 23:13

Often images are not square -landscape or portrait- which causes rendering problems or just ugly pages. Tables might have different sized rows or columns, inline images look different in each post, or rows of images appear horribly cluttered and inconsistent.
This function will add padding to your images, to make them appear in a square. But remember that this will override any padding applied to img in your stylesheets. This will also only work in image modules images, because you lmight notice that the PHP checks for sizes that are similar to the ones set for image module. That way we can be quite sure the image we display is generated by image module. "Quite", so not very sure!

This is the function you put in tempate.php, when using a phptemplate template.

<?php
/**
* Make images square.
*/
function newsphoto_image($path, $alt = '', $title = '', $attributes = '', $getsize = true) {
 
//always do getimagesize
 
if ($path && (list($width, $height, $type, $image_attributes) = @getimagesize($path))) {
   
//$sizes = _image_get_sizes(); /* To get the below stated IF dynamicly filled */
   
foreach (_image_get_sizes() as $size) {
      if(
in_array($height, $size) ||
        
in_array($width, $size) ||
        
in_array($height + 1, $size) || //rounding can cause the displayed to be one pix bigger or smaller then the size in image_get_sizes.
        
in_array($width + 1, $size) ||
        
in_array($height - 1, $size) ||
        
in_array($width - 1, $size)) {
       
//the difference between the real height and teh pico height, devided by two and a bordr of 2 pixels
       
$height = round(($size['height'] - $height)/2)+2;
       
$width = round(($size['width'] - $width)/2)+4;
       
$attributes['style'] .= 'padding:'. $height .'px '. $width .'px;';
        break;
      }
    }
  }
  return
'<img src="/'. check_url($path) .'" alt="'. check_plain($alt) .'" title="'. check_plain($title) .'" '. $image_attributes . drupal_attributes($attributes) .'/>';
}
?>

 
 

Drupal is a registered trademark of Dries Buytaert.