4 * RandomImageGenerator -- does what it says on the tin.
5 * Requires Imagick, the ImageMagick library for PHP, or the command line equivalent (usually 'convert').
7 * Because MediaWiki tests the uniqueness of media upload content, and filenames, it is sometimes useful to generate
8 * files that are guaranteed (or at least very likely) to be unique in both those ways.
9 * This generates a number of filenames with random names and random content (colored triangles)
11 * It is also useful to have fresh content because our tests currently run in a "destructive" mode, and don't create a fresh new wiki for each
13 * Consequently, if we just had a few static files we kept re-uploading, we'd get lots of warnings about matching content or filenames,
14 * and even if we deleted those files, we'd get warnings about archived files.
16 * This can also be used with a cronjob to generate random files all the time -- I use it to have a constant, never ending supply when I'm
17 * testing interactively.
20 * @author Neil Kandalgaonkar <neilk@wikimedia.org>
24 * RandomImageGenerator: does what it says on the tin.
25 * Can fetch a random image, or also write a number of them to disk with random filenames.
27 class RandomImageGenerator
{
29 private $dictionaryFile;
30 private $minWidth = 400;
31 private $maxWidth = 800;
32 private $minHeight = 400;
33 private $maxHeight = 800;
34 private $shapesToDraw = 5;
37 * Orientations: 0th row, 0th column, Exif orientation code, rotation 2x2 matrix that is opposite of orientation
38 * n.b. we do not handle the 'flipped' orientations, which is why there is no entry for 2, 4, 5, or 7. Those
39 * seem to be rare in real images anyway
40 * (we also would need a non-symmetric shape for the images to test those, like a letter F)
42 private static $orientations = array(
47 'counterRotation' => array( array( 1, 0 ), array( 0, 1 ) )
53 'counterRotation' => array( array( -1, 0 ), array( 0, -1 ) )
59 'counterRotation' => array( array( 0, 1 ), array( 1, 0 ) )
65 'counterRotation' => array( array( 0, -1 ), array( -1, 0 ) )
69 public function __construct( $options = array() ) {
70 foreach ( array( 'dictionaryFile', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight', 'shapesToDraw' ) as $property ) {
71 if ( isset( $options[$property] ) ) {
72 $this->$property = $options[$property];
76 // find the dictionary file, to generate random names
77 if ( !isset( $this->dictionaryFile
) ) {
80 '/usr/share/dict/words',
82 __DIR__
. '/words.txt'
85 if ( is_file( $dictionaryFile ) and is_readable( $dictionaryFile ) ) {
86 $this->dictionaryFile
= $dictionaryFile;
91 if ( !isset( $this->dictionaryFile
) ) {
92 throw new Exception( "RandomImageGenerator: dictionary file not found or not specified properly" );
97 * Writes random images with random filenames to disk in the directory you specify, or current working directory
99 * @param int $number number of filenames to write
100 * @param string $format optional, must be understood by ImageMagick, such as 'jpg' or 'gif'
101 * @param string $dir directory, optional (will default to current working directory)
102 * @return array filenames we just wrote
104 function writeImages( $number, $format = 'jpg', $dir = null ) {
105 $filenames = $this->getRandomFilenames( $number, $format, $dir );
106 $imageWriteMethod = $this->getImageWriteMethod( $format );
107 foreach ( $filenames as $filename ) {
108 $this->{$imageWriteMethod}( $this->getImageSpec(), $format, $filename );
115 * Figure out how we write images. This is a factor of both format and the local system
117 * @param string $format (a typical extension like 'svg', 'jpg', etc.)
122 function getImageWriteMethod( $format ) {
123 global $wgUseImageMagick, $wgImageMagickConvertCommand;
124 if ( $format === 'svg' ) {
127 // figure out how to write images
128 global $wgExiv2Command;
129 if ( class_exists( 'Imagick' ) && $wgExiv2Command && is_executable( $wgExiv2Command ) ) {
130 return 'writeImageWithApi';
131 } elseif ( $wgUseImageMagick && $wgImageMagickConvertCommand && is_executable( $wgImageMagickConvertCommand ) ) {
132 return 'writeImageWithCommandLine';
135 throw new Exception( "RandomImageGenerator: could not find a suitable method to write images in '$format' format" );
139 * Return a number of randomly-generated filenames
140 * Each filename uses two words randomly drawn from the dictionary, like elephantine_spatula.jpg
142 * @param int $number Number of filenames to generate
143 * @param string $extension Optional, defaults to 'jpg'
144 * @param string $dir Optional, defaults to current working directory
145 * @return array Array of filenames
147 private function getRandomFilenames( $number, $extension = 'jpg', $dir = null ) {
148 if ( is_null( $dir ) ) {
151 $filenames = array();
152 foreach ( $this->getRandomWordPairs( $number ) as $pair ) {
153 $basename = $pair[0] . '_' . $pair[1];
154 if ( !is_null( $extension ) ) {
155 $basename .= '.' . $extension;
157 $basename = preg_replace( '/\s+/', '', $basename );
158 $filenames[] = "$dir/$basename";
165 * Generate data representing an image of random size (within limits),
166 * consisting of randomly colored and sized upward pointing triangles against a random background color
167 * (This data is used in the writeImage* methods).
170 public function getImageSpec() {
173 $spec['width'] = mt_rand( $this->minWidth
, $this->maxWidth
);
174 $spec['height'] = mt_rand( $this->minHeight
, $this->maxHeight
);
175 $spec['fill'] = $this->getRandomColor();
177 $diagonalLength = sqrt( pow( $spec['width'], 2 ) +
pow( $spec['height'], 2 ) );
180 for ( $i = 0; $i <= $this->shapesToDraw
; $i++
) {
181 $radius = mt_rand( 0, $diagonalLength / 4 );
182 if ( $radius == 0 ) {
185 $originX = mt_rand( -1 * $radius, $spec['width'] +
$radius );
186 $originY = mt_rand( -1 * $radius, $spec['height'] +
$radius );
187 $angle = mt_rand( 0, ( 3.141592 / 2 ) * $radius ) / $radius;
188 $legDeltaX = round( $radius * sin( $angle ) );
189 $legDeltaY = round( $radius * cos( $angle ) );
192 $draw['fill'] = $this->getRandomColor();
193 $draw['shape'] = array(
194 array( 'x' => $originX, 'y' => $originY - $radius ),
195 array( 'x' => $originX +
$legDeltaX, 'y' => $originY +
$legDeltaY ),
196 array( 'x' => $originX - $legDeltaX, 'y' => $originY +
$legDeltaY ),
197 array( 'x' => $originX, 'y' => $originY - $radius )
202 $spec['draws'] = $draws;
208 * Given array( array('x' => 10, 'y' => 20), array( 'x' => 30, y=> 5 ) )
209 * returns "10,20 30,5"
210 * Useful for SVG and imagemagick command line arguments
211 * @param array $shape Array of arrays, each array containing x & y keys mapped to numeric values
214 static function shapePointsToString( $shape ) {
216 foreach ( $shape as $point ) {
217 $points[] = $point['x'] . ',' . $point['y'];
220 return join( " ", $points );
224 * Based on image specification, write a very simple SVG file to disk.
225 * Ignores the background spec because transparency is cool. :)
227 * @param array $spec spec describing background and shapes to draw
228 * @param string $format file format to write (which is obviously always svg here)
229 * @param string $filename filename to write to
233 public function writeSvg( $spec, $format, $filename ) {
234 $svg = new SimpleXmlElement( '<svg/>' );
235 $svg->addAttribute( 'xmlns', 'http://www.w3.org/2000/svg' );
236 $svg->addAttribute( 'version', '1.1' );
237 $svg->addAttribute( 'width', $spec['width'] );
238 $svg->addAttribute( 'height', $spec['height'] );
239 $g = $svg->addChild( 'g' );
240 foreach ( $spec['draws'] as $drawSpec ) {
241 $shape = $g->addChild( 'polygon' );
242 $shape->addAttribute( 'fill', $drawSpec['fill'] );
243 $shape->addAttribute( 'points', self
::shapePointsToString( $drawSpec['shape'] ) );
246 if ( !$fh = fopen( $filename, 'w' ) ) {
247 throw new Exception( "couldn't open $filename for writing" );
249 fwrite( $fh, $svg->asXML() );
250 if ( !fclose( $fh ) ) {
251 throw new Exception( "couldn't close $filename" );
256 * Based on an image specification, write such an image to disk, using Imagick PHP extension
257 * @param array $spec spec describing background and circles to draw
258 * @param string $format file format to write
259 * @param string $filename filename to write to
261 public function writeImageWithApi( $spec, $format, $filename ) {
262 // this is a hack because I can't get setImageOrientation() to work. See below.
263 global $wgExiv2Command;
265 $image = new Imagick();
267 * If the format is 'jpg', will also add a random orientation -- the image will be drawn rotated with triangle points
268 * facing in some direction (0, 90, 180 or 270 degrees) and a countering rotation should turn the triangle points upward again
270 $orientation = self
::$orientations[0]; // default is normal orientation
271 if ( $format == 'jpg' ) {
272 $orientation = self
::$orientations[array_rand( self
::$orientations )];
273 $spec = self
::rotateImageSpec( $spec, $orientation['counterRotation'] );
276 $image->newImage( $spec['width'], $spec['height'], new ImagickPixel( $spec['fill'] ) );
278 foreach ( $spec['draws'] as $drawSpec ) {
279 $draw = new ImagickDraw();
280 $draw->setFillColor( $drawSpec['fill'] );
281 $draw->polygon( $drawSpec['shape'] );
282 $image->drawImage( $draw );
285 $image->setImageFormat( $format );
287 // this doesn't work, even though it's documented to do so...
288 // $image->setImageOrientation( $orientation['exifCode'] );
290 $image->writeImage( $filename );
292 // because the above setImageOrientation call doesn't work... nor can I get an external imagemagick binary to do this either...
293 // hacking this for now (only works if you have exiv2 installed, a program to read and manipulate exif)
294 if ( $wgExiv2Command ) {
295 $cmd = wfEscapeShellArg( $wgExiv2Command )
297 . wfEscapeShellArg( "set Exif.Image.Orientation " . $orientation['exifCode'] )
299 . wfEscapeShellArg( $filename );
302 $err = wfShellExec( $cmd, $retval );
303 if ( $retval !== 0 ) {
304 print "Error with $cmd: $retval, $err\n";
310 * Given an image specification, produce rotated version
311 * This is used when simulating a rotated image capture with Exif orientation
312 * @param $spec Object returned by getImageSpec
313 * @param $matrix 2x2 transformation matrix
314 * @return array transformed Spec
316 private static function rotateImageSpec( &$spec, $matrix ) {
318 $dims = self
::matrixMultiply2x2( $matrix, $spec['width'], $spec['height'] );
321 if ( $dims['x'] < 0 ) {
322 $correctionX = abs( $dims['x'] );
324 if ( $dims['y'] < 0 ) {
325 $correctionY = abs( $dims['y'] );
327 $tSpec['width'] = abs( $dims['x'] );
328 $tSpec['height'] = abs( $dims['y'] );
329 $tSpec['fill'] = $spec['fill'];
330 $tSpec['draws'] = array();
331 foreach ( $spec['draws'] as $draw ) {
333 'fill' => $draw['fill'],
336 foreach ( $draw['shape'] as $point ) {
337 $tPoint = self
::matrixMultiply2x2( $matrix, $point['x'], $point['y'] );
338 $tPoint['x'] +
= $correctionX;
339 $tPoint['y'] +
= $correctionY;
340 $tDraw['shape'][] = $tPoint;
342 $tSpec['draws'][] = $tDraw;
349 * Given a matrix and a pair of images, return new position
350 * @param array $matrix 2x2 rotation matrix
351 * @param int $x x-coordinate number
352 * @param int $y y-coordinate number
353 * @return array Transformed with properties x, y
355 private static function matrixMultiply2x2( $matrix, $x, $y ) {
357 'x' => $x * $matrix[0][0] +
$y * $matrix[0][1],
358 'y' => $x * $matrix[1][0] +
$y * $matrix[1][1]
363 * Based on an image specification, write such an image to disk, using the command line ImageMagick program ('convert').
365 * Sample command line:
366 * $ convert -size 100x60 xc:rgb(90,87,45) \
367 * -draw 'fill rgb(12,34,56) polygon 41,39 44,57 50,57 41,39' \
368 * -draw 'fill rgb(99,123,231) circle 59,39 56,57' \
369 * -draw 'fill rgb(240,12,32) circle 50,21 50,3' filename.png
371 * @param array $spec spec describing background and shapes to draw
372 * @param string $format file format to write (unused by this method but kept so it has the same signature as
374 * @param string $filename filename to write to
378 public function writeImageWithCommandLine( $spec, $format, $filename ) {
379 global $wgImageMagickConvertCommand;
381 $args[] = "-size " . wfEscapeShellArg( $spec['width'] . 'x' . $spec['height'] );
382 $args[] = wfEscapeShellArg( "xc:" . $spec['fill'] );
383 foreach ( $spec['draws'] as $draw ) {
384 $fill = $draw['fill'];
385 $polygon = self
::shapePointsToString( $draw['shape'] );
386 $drawCommand = "fill $fill polygon $polygon";
387 $args[] = '-draw ' . wfEscapeShellArg( $drawCommand );
389 $args[] = wfEscapeShellArg( $filename );
391 $command = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " . implode( " ", $args );
393 wfShellExec( $command, $retval );
395 return ( $retval === 0 );
399 * Generate a string of random colors for ImageMagick or SVG, like "rgb(12, 37, 98)"
403 public function getRandomColor() {
404 $components = array();
405 for ( $i = 0; $i <= 2; $i++
) {
406 $components[] = mt_rand( 0, 255 );
409 return 'rgb(' . join( ', ', $components ) . ')';
413 * Get an array of random pairs of random words, like array( array( 'foo', 'bar' ), array( 'quux', 'baz' ) );
415 * @param int $number Number of pairs
416 * @return array two-element arrays
418 private function getRandomWordPairs( $number ) {
419 $lines = $this->getRandomLines( $number * 2 );
420 // construct pairs of words
422 $count = count( $lines );
423 for ( $i = 0; $i < $count; $i +
= 2 ) {
424 $pairs[] = array( $lines[$i], $lines[$i +
1] );
431 * Return N random lines from a file
433 * Will throw exception if the file could not be read or if it had fewer lines than requested.
435 * @param int $number_desired number of lines desired
438 * @return array of exactly n elements, drawn randomly from lines the file
440 private function getRandomLines( $number_desired ) {
441 $filepath = $this->dictionaryFile
;
443 // initialize array of lines
445 for ( $i = 0; $i < $number_desired; $i++
) {
450 * This algorithm obtains N random lines from a file in one single pass. It does this by replacing elements of
451 * a fixed-size array of lines, less and less frequently as it reads the file.
453 $fh = fopen( $filepath, "r" );
455 throw new Exception( "couldn't open $filepath" );
458 $max_index = $number_desired - 1;
459 while ( !feof( $fh ) ) {
460 $line = fgets( $fh );
461 if ( $line !== false ) {
463 $line = trim( $line );
464 if ( mt_rand( 0, $line_number ) <= $max_index ) {
465 $lines[mt_rand( 0, $max_index )] = $line;
470 if ( $line_number < $number_desired ) {
471 throw new Exception( "not enough lines in $filepath" );