May 16 2010

PHP Snippet: how to auto-crop image for thumbnail using imagemagick.

Posted by German Rumm in php

Had a need to create thumbnails of specified size for a site, but source images were of different dimensions.

Usually I use some kind of framework/plugin function for that, but this project is pure PHP, so I had to come up with a function. I did this several times already and I don’t like writing the same function over and over again. So, here’s the snippet which I can look up later. Maybe someone else will also find it useful:

/**
 * $image_path string Path to an image file.
 * $size string Thumbnail dimensions in <width>x<height> format
 * 
 * @returns string Path to created thumbnail
 */
function thumbnail($image_path, $size = '200x150') {
  list($width, $height) = getimagesize($image_path);
  $image_aspect = $width / $height;
 
  list($thumb_width, $thumb_height) = explode('x', $size);
  $thumb_aspect = $thumb_width / $thumb_height;
 
  if ($image_aspect > $thumb_aspect) {
    $crop_height = $height;
    $crop_width = round($crop_height * $thumb_aspect);
  } else {
    $crop_width = $width;
    $crop_height = round($crop_width / $thumb_aspect);
  }
 
  $crop_x_offset = round(($width - $crop_width) / 2);
  $crop_y_offset = round(($height - $crop_height) / 2);
 
  // crop parameter
  $crop_size = $crop_width.'x'.$crop_height.'+'.$crop_x_offset.'+'.$crop_y_offset;
 
  // thumbnail is created next to original image with th- prefix.
  $thumb = dirname($image_path).'/th-'.basename($image);
  exec('convert '. escapeshellarg($path).' -crop ' . $crop_size .' -thumbnail '.$size.' '. escapeshellarg($thumb));
 
  return $thumb;
}
Mar 28 2007

XDebug’s CodeCoverage renderer with Geshi

Posted by German Rumm in Uncategorized

Found XDebug yesterday, great PHP extension.

Now my custom Reporter class for Simpletest includes code coverage report.

But to make things really look cool, I wrote CodeCoverageRenderer that uses modified version of Geshi. It has only one method – render() and accepts array returned by xdebug_get_code_coverage() in constructor.

Looks like this:

CodeCoverageRenderer example

Nice, huh?

Usage

	xdebug_start_code_coverage(XDEBUG_CC_UNUSED); // this is needed for percentage.
	// ... some code here
	require_once('CodeCoverageRenderer.php');
	$renderer = new CodeCoverageRenderer(xdebug_get_code_coverage());
	$renderer->render();

Download

Download CodeCoverageRenderer.zip (Geshi w/ PHP support included)