Views template override function for a field to pad top of an image to center it

This method is dependent on running the images through an image style to ensure that the width and height tags are added to the img tag, and that the height of the area to be centered is known. This is pretty easy for fixed sized areas fitting images, like in a list or gallery.

Instead of making a views-view-field--featured--field-image-cache-fid.tpl.php file, this function produced the output instead. In this example, I know that the height of the div is of a fixed 155px in height.

function MYMODULE_views_view_field__featured__field_image_cache_fid($view, $field, $row) {
 
  // Use the default renderer to get the output of the field normally.
  $result = $view->field[$field->options['id']]->advanced_render($row);
 
  // output is now something like
  // <a href="/products/example-product-one" class="imagecache imagecache-featured imagecache-linked imagecache-featured_linked"><img src="http://example.com/sites/example/files/imagecache/featured/product/example-product-one.jpg" alt="" title=""  class="imagecache imagecache-featured" width="110" height="123" /></a>
 
  // Match the height and pad the top by half the height difference from 155
  $height_should_be = 155;
  if (preg_match('/ height="(.*)" /', $result, $matches)) {
    if ($matches[1] < 154) {
      $pad = floor(($height_should_be - $matches[1]) / 2);
      return str_replace('<img ', '<img style="margin-top: ' . $pad . 'px;" ', $result);
    }
  }
 
  return $result;
}