MediaWiki  REL1_21
RandomImageGenerator.php
Go to the documentation of this file.
00001 <?php
00002 
00027 class RandomImageGenerator {
00028 
00029         private $dictionaryFile;
00030         private $minWidth = 400;
00031         private $maxWidth = 800;
00032         private $minHeight = 400;
00033         private $maxHeight = 800;
00034         private $shapesToDraw = 5;
00035 
00042         private static $orientations = array(
00043                 array(
00044                         '0thRow' => 'top',
00045                         '0thCol' => 'left',
00046                         'exifCode' => 1,
00047                         'counterRotation' => array( array( 1, 0 ), array( 0, 1 ) )
00048                 ),
00049                 array(
00050                         '0thRow' => 'bottom',
00051                         '0thCol' => 'right',
00052                         'exifCode' => 3,
00053                         'counterRotation' => array( array( -1, 0 ), array( 0, -1 ) )
00054                 ),
00055                 array(
00056                         '0thRow' => 'right',
00057                         '0thCol' => 'top',
00058                         'exifCode' => 6,
00059                         'counterRotation' => array( array( 0, 1 ), array( 1, 0 ) )
00060                 ),
00061                 array(
00062                         '0thRow' => 'left',
00063                         '0thCol' => 'bottom',
00064                         'exifCode' => 8,
00065                         'counterRotation' => array( array( 0, -1 ), array( -1, 0 ) )
00066                 )
00067         );
00068 
00069 
00070         public function __construct( $options = array() ) {
00071                 foreach ( array( 'dictionaryFile', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight', 'shapesToDraw' ) as $property ) {
00072                         if ( isset( $options[$property] ) ) {
00073                                 $this->$property = $options[$property];
00074                         }
00075                 }
00076 
00077                 // find the dictionary file, to generate random names
00078                 if ( !isset( $this->dictionaryFile ) ) {
00079                         foreach (
00080                                 array(
00081                                         '/usr/share/dict/words',
00082                                         '/usr/dict/words',
00083                                         __DIR__ . '/words.txt'
00084                                 ) as $dictionaryFile
00085                         ) {
00086                                 if ( is_file( $dictionaryFile ) and is_readable( $dictionaryFile ) ) {
00087                                         $this->dictionaryFile = $dictionaryFile;
00088                                         break;
00089                                 }
00090                         }
00091                 }
00092                 if ( !isset( $this->dictionaryFile ) ) {
00093                         throw new Exception( "RandomImageGenerator: dictionary file not found or not specified properly" );
00094                 }
00095         }
00096 
00105         function writeImages( $number, $format = 'jpg', $dir = null ) {
00106                 $filenames = $this->getRandomFilenames( $number, $format, $dir );
00107                 $imageWriteMethod = $this->getImageWriteMethod( $format );
00108                 foreach ( $filenames as $filename ) {
00109                         $this->{$imageWriteMethod}( $this->getImageSpec(), $format, $filename );
00110                 }
00111                 return $filenames;
00112         }
00113 
00114 
00119         function getImageWriteMethod( $format ) {
00120                 global $wgUseImageMagick, $wgImageMagickConvertCommand;
00121                 if ( $format === 'svg' ) {
00122                         return 'writeSvg';
00123                 } else {
00124                         // figure out how to write images
00125                         global $wgExiv2Command;
00126                         if ( class_exists( 'Imagick' ) && $wgExiv2Command && is_executable( $wgExiv2Command ) ) {
00127                                 return 'writeImageWithApi';
00128                         } elseif ( $wgUseImageMagick && $wgImageMagickConvertCommand && is_executable( $wgImageMagickConvertCommand ) ) {
00129                                 return 'writeImageWithCommandLine';
00130                         }
00131                 }
00132                 throw new Exception( "RandomImageGenerator: could not find a suitable method to write images in '$format' format" );
00133         }
00134 
00144         private function getRandomFilenames( $number, $extension = 'jpg', $dir = null ) {
00145                 if ( is_null( $dir ) ) {
00146                         $dir = getcwd();
00147                 }
00148                 $filenames = array();
00149                 foreach ( $this->getRandomWordPairs( $number ) as $pair ) {
00150                         $basename = $pair[0] . '_' . $pair[1];
00151                         if ( !is_null( $extension ) ) {
00152                                 $basename .= '.' . $extension;
00153                         }
00154                         $basename = preg_replace( '/\s+/', '', $basename );
00155                         $filenames[] = "$dir/$basename";
00156                 }
00157 
00158                 return $filenames;
00159 
00160         }
00161 
00162 
00169         public function getImageSpec() {
00170                 $spec = array();
00171 
00172                 $spec['width'] = mt_rand( $this->minWidth, $this->maxWidth );
00173                 $spec['height'] = mt_rand( $this->minHeight, $this->maxHeight );
00174                 $spec['fill'] = $this->getRandomColor();
00175 
00176                 $diagonalLength = sqrt( pow( $spec['width'], 2 ) + pow( $spec['height'], 2 ) );
00177 
00178                 $draws = array();
00179                 for ( $i = 0; $i <= $this->shapesToDraw; $i++ ) {
00180                         $radius = mt_rand( 0, $diagonalLength / 4 );
00181                         if ( $radius == 0 ) {
00182                                 continue;
00183                         }
00184                         $originX = mt_rand( -1 * $radius, $spec['width'] + $radius );
00185                         $originY = mt_rand( -1 * $radius, $spec['height'] + $radius );
00186                         $angle = mt_rand( 0, ( 3.141592 / 2 ) * $radius ) / $radius;
00187                         $legDeltaX = round( $radius * sin( $angle ) );
00188                         $legDeltaY = round( $radius * cos( $angle ) );
00189 
00190                         $draw = array();
00191                         $draw['fill'] = $this->getRandomColor();
00192                         $draw['shape'] = array(
00193                                 array( 'x' => $originX, 'y' => $originY - $radius ),
00194                                 array( 'x' => $originX + $legDeltaX, 'y' => $originY + $legDeltaY ),
00195                                 array( 'x' => $originX - $legDeltaX, 'y' => $originY + $legDeltaY ),
00196                                 array( 'x' => $originX, 'y' => $originY - $radius )
00197                         );
00198                         $draws[] = $draw;
00199 
00200                 }
00201 
00202                 $spec['draws'] = $draws;
00203 
00204                 return $spec;
00205         }
00206 
00214         static function shapePointsToString( $shape ) {
00215                 $points = array();
00216                 foreach ( $shape as $point ) {
00217                         $points[] = $point['x'] . ',' . $point['y'];
00218                 }
00219                 return join( " ", $points );
00220         }
00221 
00229         public function writeSvg( $spec, $format, $filename ) {
00230                 $svg = new SimpleXmlElement( '<svg/>' );
00231                 $svg->addAttribute( 'xmlns', 'http://www.w3.org/2000/svg' );
00232                 $svg->addAttribute( 'version', '1.1' );
00233                 $svg->addAttribute( 'width', $spec['width'] );
00234                 $svg->addAttribute( 'height', $spec['height'] );
00235                 $g = $svg->addChild( 'g' );
00236                 foreach ( $spec['draws'] as $drawSpec ) {
00237                         $shape = $g->addChild( 'polygon' );
00238                         $shape->addAttribute( 'fill', $drawSpec['fill'] );
00239                         $shape->addAttribute( 'points', self::shapePointsToString( $drawSpec['shape'] ) );
00240                 }
00241 
00242                 if ( !$fh = fopen( $filename, 'w' ) ) {
00243                         throw new Exception( "couldn't open $filename for writing" );
00244                 }
00245                 fwrite( $fh, $svg->asXML() );
00246                 if ( !fclose( $fh ) ) {
00247                         throw new Exception( "couldn't close $filename" );
00248                 }
00249         }
00250 
00257         public function writeImageWithApi( $spec, $format, $filename ) {
00258                 // this is a hack because I can't get setImageOrientation() to work. See below.
00259                 global $wgExiv2Command;
00260 
00261                 $image = new Imagick();
00266                 $orientation = self::$orientations[0]; // default is normal orientation
00267                 if ( $format == 'jpg' ) {
00268                         $orientation = self::$orientations[array_rand( self::$orientations )];
00269                         $spec = self::rotateImageSpec( $spec, $orientation['counterRotation'] );
00270                 }
00271 
00272                 $image->newImage( $spec['width'], $spec['height'], new ImagickPixel( $spec['fill'] ) );
00273 
00274                 foreach ( $spec['draws'] as $drawSpec ) {
00275                         $draw = new ImagickDraw();
00276                         $draw->setFillColor( $drawSpec['fill'] );
00277                         $draw->polygon( $drawSpec['shape'] );
00278                         $image->drawImage( $draw );
00279                 }
00280 
00281                 $image->setImageFormat( $format );
00282 
00283                 // this doesn't work, even though it's documented to do so...
00284                 // $image->setImageOrientation( $orientation['exifCode'] );
00285 
00286                 $image->writeImage( $filename );
00287 
00288                 // because the above setImageOrientation call doesn't work... nor can I get an external imagemagick binary to do this either...
00289                 // hacking this for now (only works if you have exiv2 installed, a program to read and manipulate exif)
00290                 if ( $wgExiv2Command ) {
00291                         $cmd = wfEscapeShellArg( $wgExiv2Command )
00292                                 . " -M "
00293                                 . wfEscapeShellArg( "set Exif.Image.Orientation " . $orientation['exifCode'] )
00294                                 . " "
00295                                 . wfEscapeShellArg( $filename );
00296 
00297                         $retval = 0;
00298                         $err = wfShellExec( $cmd, $retval );
00299                         if ( $retval !== 0 ) {
00300                                 print "Error with $cmd: $retval, $err\n";
00301                         }
00302                 }
00303         }
00304 
00312         private static function rotateImageSpec( &$spec, $matrix ) {
00313                 $tSpec = array();
00314                 $dims = self::matrixMultiply2x2( $matrix, $spec['width'], $spec['height'] );
00315                 $correctionX = 0;
00316                 $correctionY = 0;
00317                 if ( $dims['x'] < 0 ) {
00318                         $correctionX = abs( $dims['x'] );
00319                 }
00320                 if ( $dims['y'] < 0 ) {
00321                         $correctionY = abs( $dims['y'] );
00322                 }
00323                 $tSpec['width'] = abs( $dims['x'] );
00324                 $tSpec['height'] = abs( $dims['y'] );
00325                 $tSpec['fill'] = $spec['fill'];
00326                 $tSpec['draws'] = array();
00327                 foreach ( $spec['draws'] as $draw ) {
00328                         $tDraw = array(
00329                                 'fill' => $draw['fill'],
00330                                 'shape' => array()
00331                         );
00332                         foreach ( $draw['shape'] as $point ) {
00333                                 $tPoint = self::matrixMultiply2x2( $matrix, $point['x'], $point['y'] );
00334                                 $tPoint['x'] += $correctionX;
00335                                 $tPoint['y'] += $correctionY;
00336                                 $tDraw['shape'][] = $tPoint;
00337                         }
00338                         $tSpec['draws'][] = $tDraw;
00339                 }
00340                 return $tSpec;
00341         }
00342 
00350         private static function matrixMultiply2x2( $matrix, $x, $y ) {
00351                 return array(
00352                         'x' => $x * $matrix[0][0] + $y * $matrix[0][1],
00353                         'y' => $x * $matrix[1][0] + $y * $matrix[1][1]
00354                 );
00355         }
00356 
00357 
00371         public function writeImageWithCommandLine( $spec, $format, $filename ) {
00372                 global $wgImageMagickConvertCommand;
00373                 $args = array();
00374                 $args[] = "-size " . wfEscapeShellArg( $spec['width'] . 'x' . $spec['height'] );
00375                 $args[] = wfEscapeShellArg( "xc:" . $spec['fill'] );
00376                 foreach ( $spec['draws'] as $draw ) {
00377                         $fill = $draw['fill'];
00378                         $polygon = self::shapePointsToString( $draw['shape'] );
00379                         $drawCommand = "fill $fill  polygon $polygon";
00380                         $args[] = '-draw ' . wfEscapeShellArg( $drawCommand );
00381                 }
00382                 $args[] = wfEscapeShellArg( $filename );
00383 
00384                 $command = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " . implode( " ", $args );
00385                 $retval = null;
00386                 wfShellExec( $command, $retval );
00387                 return ( $retval === 0 );
00388         }
00389 
00395         public function getRandomColor() {
00396                 $components = array();
00397                 for ( $i = 0; $i <= 2; $i++ ) {
00398                         $components[] = mt_rand( 0, 255 );
00399                 }
00400                 return 'rgb(' . join( ', ', $components ) . ')';
00401         }
00402 
00409         private function getRandomWordPairs( $number ) {
00410                 $lines = $this->getRandomLines( $number * 2 );
00411                 // construct pairs of words
00412                 $pairs = array();
00413                 $count = count( $lines );
00414                 for ( $i = 0; $i < $count; $i += 2 ) {
00415                         $pairs[] = array( $lines[$i], $lines[$i + 1] );
00416                 }
00417                 return $pairs;
00418         }
00419 
00428         private function getRandomLines( $number_desired ) {
00429                 $filepath = $this->dictionaryFile;
00430 
00431                 // initialize array of lines
00432                 $lines = array();
00433                 for ( $i = 0; $i < $number_desired; $i++ ) {
00434                         $lines[] = null;
00435                 }
00436 
00437                 /*
00438                  * This algorithm obtains N random lines from a file in one single pass. It does this by replacing elements of
00439                  * a fixed-size array of lines, less and less frequently as it reads the file.
00440                  */
00441                 $fh = fopen( $filepath, "r" );
00442                 if ( !$fh ) {
00443                         throw new Exception( "couldn't open $filepath" );
00444                 }
00445                 $line_number = 0;
00446                 $max_index = $number_desired - 1;
00447                 while ( !feof( $fh ) ) {
00448                         $line = fgets( $fh );
00449                         if ( $line !== false ) {
00450                                 $line_number++;
00451                                 $line = trim( $line );
00452                                 if ( mt_rand( 0, $line_number ) <= $max_index ) {
00453                                         $lines[mt_rand( 0, $max_index )] = $line;
00454                                 }
00455                         }
00456                 }
00457                 fclose( $fh );
00458                 if ( $line_number < $number_desired ) {
00459                         throw new Exception( "not enough lines in $filepath" );
00460                 }
00461 
00462                 return $lines;
00463         }
00464 
00465 }