Category Archive for PHP

phpThumb and imagerotate()

One of the PHP libraries I use the most is phpThumb, because of its ease to use and portability. Simply putting the folder in the web root is usually sufficient to get started. One thing has annoyed me for a while though, and it is that I couldn’t get the rotating commands to work.

After some research I discovered that the imagerotate() function in GD library (a library that handles many of the graphics processing in phpThumb) is only available in the bundled version of GD library (that is: the version that sometimes comes bundled with PHP). That is not the case for me and I have my own server with lots of sites on, and didn’t feel like recompiling PHP just to get the imagerotate function to work.

So, in this new light, I looked for a function replacement using ImageMagick instead (a much better image processing library, but rarely installed by default) and found this one somewhere. Simply put it at the bottom of your phpthumb.functions.php file and *poof* rotating images in phpThumb will start working.

if ( !function_exists( 'imagerotate' ) ) {
  1.     function imagerotate( $source_image, $angle, $bgd_color=null ) {
  2.         $angle = 360-$angle; // GD rotates CCW, imagick rotates CW
  3.         $temp_src = '/tmp/temp_src.png';
  4.         $temp_dst = '/tmp/temp_dst.png';
  5.         if (!imagepng($source_image,$temp_src)){
  6.             return false;
  7.         }
  8.         $imagick = new Imagick();
  9.         $imagick->readImage($temp_src);
  10.         $imagick->rotateImage(new ImagickPixel(), $angle);
  11.         $imagick->writeImage($temp_dst);
  12.         //trigger_error( 'imagerotate(): could not write to ' . $file1 . ', original image returned', E_USER_WARNING );
  13.         $result = imagecreatefrompng($temp_dst);
  14.         unlink($temp_dst);
  15.         unlink($temp_src);
  16.         return $result;
  17.     }
  18. }
  • Share/Bookmark