MediaWiki  REL1_22
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 
00112         return $filenames;
00113     }
00114 
00115 
00120     function getImageWriteMethod( $format ) {
00121         global $wgUseImageMagick, $wgImageMagickConvertCommand;
00122         if ( $format === 'svg' ) {
00123             return 'writeSvg';
00124         } else {
00125             // figure out how to write images
00126             global $wgExiv2Command;
00127             if ( class_exists( 'Imagick' ) && $wgExiv2Command && is_executable( $wgExiv2Command ) ) {
00128                 return 'writeImageWithApi';
00129             } elseif ( $wgUseImageMagick && $wgImageMagickConvertCommand && is_executable( $wgImageMagickConvertCommand ) ) {
00130                 return 'writeImageWithCommandLine';
00131             }
00132         }
00133         throw new Exception( "RandomImageGenerator: could not find a suitable method to write images in '$format' format" );
00134     }
00135 
00145     private function getRandomFilenames( $number, $extension = 'jpg', $dir = null ) {
00146         if ( is_null( $dir ) ) {
00147             $dir = getcwd();
00148         }
00149         $filenames = array();
00150         foreach ( $this->getRandomWordPairs( $number ) as $pair ) {
00151             $basename = $pair[0] . '_' . $pair[1];
00152             if ( !is_null( $extension ) ) {
00153                 $basename .= '.' . $extension;
00154             }
00155             $basename = preg_replace( '/\s+/', '', $basename );
00156             $filenames[] = "$dir/$basename";
00157         }
00158 
00159         return $filenames;
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         $spec['draws'] = $draws;
00202 
00203         return $spec;
00204     }
00205 
00213     static function shapePointsToString( $shape ) {
00214         $points = array();
00215         foreach ( $shape as $point ) {
00216             $points[] = $point['x'] . ',' . $point['y'];
00217         }
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 
00341         return $tSpec;
00342     }
00343 
00351     private static function matrixMultiply2x2( $matrix, $x, $y ) {
00352         return array(
00353             'x' => $x * $matrix[0][0] + $y * $matrix[0][1],
00354             'y' => $x * $matrix[1][0] + $y * $matrix[1][1]
00355         );
00356     }
00357 
00358 
00372     public function writeImageWithCommandLine( $spec, $format, $filename ) {
00373         global $wgImageMagickConvertCommand;
00374         $args = array();
00375         $args[] = "-size " . wfEscapeShellArg( $spec['width'] . 'x' . $spec['height'] );
00376         $args[] = wfEscapeShellArg( "xc:" . $spec['fill'] );
00377         foreach ( $spec['draws'] as $draw ) {
00378             $fill = $draw['fill'];
00379             $polygon = self::shapePointsToString( $draw['shape'] );
00380             $drawCommand = "fill $fill  polygon $polygon";
00381             $args[] = '-draw ' . wfEscapeShellArg( $drawCommand );
00382         }
00383         $args[] = wfEscapeShellArg( $filename );
00384 
00385         $command = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " . implode( " ", $args );
00386         $retval = null;
00387         wfShellExec( $command, $retval );
00388 
00389         return ( $retval === 0 );
00390     }
00391 
00397     public function getRandomColor() {
00398         $components = array();
00399         for ( $i = 0; $i <= 2; $i++ ) {
00400             $components[] = mt_rand( 0, 255 );
00401         }
00402 
00403         return 'rgb(' . join( ', ', $components ) . ')';
00404     }
00405 
00412     private function getRandomWordPairs( $number ) {
00413         $lines = $this->getRandomLines( $number * 2 );
00414         // construct pairs of words
00415         $pairs = array();
00416         $count = count( $lines );
00417         for ( $i = 0; $i < $count; $i += 2 ) {
00418             $pairs[] = array( $lines[$i], $lines[$i + 1] );
00419         }
00420 
00421         return $pairs;
00422     }
00423 
00432     private function getRandomLines( $number_desired ) {
00433         $filepath = $this->dictionaryFile;
00434 
00435         // initialize array of lines
00436         $lines = array();
00437         for ( $i = 0; $i < $number_desired; $i++ ) {
00438             $lines[] = null;
00439         }
00440 
00441         /*
00442          * This algorithm obtains N random lines from a file in one single pass. It does this by replacing elements of
00443          * a fixed-size array of lines, less and less frequently as it reads the file.
00444          */
00445         $fh = fopen( $filepath, "r" );
00446         if ( !$fh ) {
00447             throw new Exception( "couldn't open $filepath" );
00448         }
00449         $line_number = 0;
00450         $max_index = $number_desired - 1;
00451         while ( !feof( $fh ) ) {
00452             $line = fgets( $fh );
00453             if ( $line !== false ) {
00454                 $line_number++;
00455                 $line = trim( $line );
00456                 if ( mt_rand( 0, $line_number ) <= $max_index ) {
00457                     $lines[mt_rand( 0, $max_index )] = $line;
00458                 }
00459             }
00460         }
00461         fclose( $fh );
00462         if ( $line_number < $number_desired ) {
00463             throw new Exception( "not enough lines in $filepath" );
00464         }
00465 
00466         return $lines;
00467     }
00468 }