3 * RandomImageGenerator -- does what it says on the tin.
4 * Requires Imagick, the ImageMagick library for PHP, or the command line
5 * equivalent (usually 'convert').
7 * Because MediaWiki tests the uniqueness of media upload content, and
8 * filenames, it is sometimes useful to generate files that are guaranteed (or
9 * at least very likely) to be unique in both those ways. This generates a
10 * number of filenames with random names and random content (colored triangles).
12 * It is also useful to have fresh content because our tests currently run in a
13 * "destructive" mode, and don't create a fresh new wiki for each test run.
14 * Consequently, if we just had a few static files we kept re-uploading, we'd
15 * get lots of warnings about matching content or filenames, and even if we
16 * deleted those files, we'd get warnings about archived files.
18 * This can also be used with a cronjob to generate random files all the time.
19 * I use it to have a constant, never ending supply when I'm testing
23 * @author Neil Kandalgaonkar <neilk@wikimedia.org>
26 use MediaWiki\Shell\Shell
;
29 * RandomImageGenerator: does what it says on the tin.
30 * Can fetch a random image, or also write a number of them to disk with random filenames.
32 class RandomImageGenerator
{
33 private $dictionaryFile;
34 private $minWidth = 400;
35 private $maxWidth = 800;
36 private $minHeight = 400;
37 private $maxHeight = 800;
38 private $shapesToDraw = 5;
41 * Orientations: 0th row, 0th column, Exif orientation code, rotation 2x2
42 * matrix that is opposite of orientation. N.b. we do not handle the
43 * 'flipped' orientations, which is why there is no entry for 2, 4, 5, or 7.
44 * Those seem to be rare in real images anyway (we also would need a
45 * non-symmetric shape for the images to test those, like a letter F).
47 private static $orientations = [
52 'counterRotation' => [ [ 1, 0 ], [ 0, 1 ] ]
58 'counterRotation' => [ [ -1, 0 ], [ 0, -1 ] ]
64 'counterRotation' => [ [ 0, 1 ], [ 1, 0 ] ]
70 'counterRotation' => [ [ 0, -1 ], [ -1, 0 ] ]
74 public function __construct( $options = [] ) {
75 foreach ( [ 'dictionaryFile', 'minWidth', 'minHeight',
76 'maxWidth', 'maxHeight', 'shapesToDraw' ] as $property
78 if ( isset( $options[$property] ) ) {
79 $this->$property = $options[$property];
83 // find the dictionary file, to generate random names
84 if ( !isset( $this->dictionaryFile
) ) {
87 '/usr/share/dict/words',
89 __DIR__
. '/words.txt'
92 if ( is_file( $dictionaryFile ) && is_readable( $dictionaryFile ) ) {
93 $this->dictionaryFile
= $dictionaryFile;
98 if ( !isset( $this->dictionaryFile
) ) {
99 throw new Exception( "RandomImageGenerator: dictionary file not "
100 . "found or not specified properly" );
105 * Writes random images with random filenames to disk in the directory you
106 * specify, or current working directory.
108 * @param int $number Number of filenames to write
109 * @param string $format Optional, must be understood by ImageMagick, such as 'jpg' or 'gif'
110 * @param string|null $dir Directory, optional (will default to current working directory)
111 * @return array Filenames we just wrote
113 function writeImages( $number, $format = 'jpg', $dir = null ) {
114 $filenames = $this->getRandomFilenames( $number, $format, $dir );
115 $imageWriteMethod = $this->getImageWriteMethod( $format );
116 foreach ( $filenames as $filename ) {
117 $this->{$imageWriteMethod}( $this->getImageSpec(), $format, $filename );
124 * Figure out how we write images. This is a factor of both format and the local system
126 * @param string $format (a typical extension like 'svg', 'jpg', etc.)
131 function getImageWriteMethod( $format ) {
132 global $wgUseImageMagick, $wgImageMagickConvertCommand;
133 if ( $format === 'svg' ) {
136 // figure out how to write images
137 global $wgExiv2Command;
138 if ( class_exists( 'Imagick' ) && $wgExiv2Command && is_executable( $wgExiv2Command ) ) {
139 return 'writeImageWithApi';
140 } elseif ( $wgUseImageMagick
141 && $wgImageMagickConvertCommand
142 && is_executable( $wgImageMagickConvertCommand )
144 return 'writeImageWithCommandLine';
147 throw new Exception( "RandomImageGenerator: could not find a suitable "
148 . "method to write images in '$format' format" );
152 * Return a number of randomly-generated filenames
153 * Each filename uses two words randomly drawn from the dictionary, like elephantine_spatula.jpg
155 * @param int $number Number of filenames to generate
156 * @param string $extension Optional, defaults to 'jpg'
157 * @param string $dir Optional, defaults to current working directory
158 * @return array Array of filenames
160 private function getRandomFilenames( $number, $extension = 'jpg', $dir = null ) {
161 if ( is_null( $dir ) ) {
165 foreach ( $this->getRandomWordPairs( $number ) as $pair ) {
166 $basename = $pair[0] . '_' . $pair[1];
167 if ( !is_null( $extension ) ) {
168 $basename .= '.' . $extension;
170 $basename = preg_replace( '/\s+/', '', $basename );
171 $filenames[] = "$dir/$basename";
178 * Generate data representing an image of random size (within limits),
179 * consisting of randomly colored and sized upward pointing triangles
180 * against a random background color. (This data is used in the
181 * writeImage* methods).
185 public function getImageSpec() {
188 $spec['width'] = mt_rand( $this->minWidth
, $this->maxWidth
);
189 $spec['height'] = mt_rand( $this->minHeight
, $this->maxHeight
);
190 $spec['fill'] = $this->getRandomColor();
192 $diagonalLength = sqrt( $spec['width'] ** 2 +
$spec['height'] ** 2 );
195 for ( $i = 0; $i <= $this->shapesToDraw
; $i++
) {
196 $radius = mt_rand( 0, $diagonalLength / 4 );
197 if ( $radius == 0 ) {
200 $originX = mt_rand( -1 * $radius, $spec['width'] +
$radius );
201 $originY = mt_rand( -1 * $radius, $spec['height'] +
$radius );
202 $angle = mt_rand( 0, ( 3.141592 / 2 ) * $radius ) / $radius;
203 $legDeltaX = round( $radius * sin( $angle ) );
204 $legDeltaY = round( $radius * cos( $angle ) );
207 $draw['fill'] = $this->getRandomColor();
209 [ 'x' => $originX, 'y' => $originY - $radius ],
210 [ 'x' => $originX +
$legDeltaX, 'y' => $originY +
$legDeltaY ],
211 [ 'x' => $originX - $legDeltaX, 'y' => $originY +
$legDeltaY ],
212 [ 'x' => $originX, 'y' => $originY - $radius ]
217 $spec['draws'] = $draws;
223 * Given [ [ 'x' => 10, 'y' => 20 ], [ 'x' => 30, y=> 5 ] ]
224 * returns "10,20 30,5"
225 * Useful for SVG and imagemagick command line arguments
226 * @param array $shape Array of arrays, each array containing x & y keys mapped to numeric values
229 static function shapePointsToString( $shape ) {
231 foreach ( $shape as $point ) {
232 $points[] = $point['x'] . ',' . $point['y'];
235 return implode( " ", $points );
239 * Based on image specification, write a very simple SVG file to disk.
240 * Ignores the background spec because transparency is cool. :)
242 * @param array $spec Spec describing background and shapes to draw
243 * @param string $format File format to write (which is obviously always svg here)
244 * @param string $filename Filename to write to
248 public function writeSvg( $spec, $format, $filename ) {
249 $svg = new SimpleXmlElement( '<svg/>' );
250 $svg->addAttribute( 'xmlns', 'http://www.w3.org/2000/svg' );
251 $svg->addAttribute( 'version', '1.1' );
252 $svg->addAttribute( 'width', $spec['width'] );
253 $svg->addAttribute( 'height', $spec['height'] );
254 $g = $svg->addChild( 'g' );
255 foreach ( $spec['draws'] as $drawSpec ) {
256 $shape = $g->addChild( 'polygon' );
257 $shape->addAttribute( 'fill', $drawSpec['fill'] );
258 $shape->addAttribute( 'points', self
::shapePointsToString( $drawSpec['shape'] ) );
261 $fh = fopen( $filename, 'w' );
263 throw new Exception( "couldn't open $filename for writing" );
265 fwrite( $fh, $svg->asXML() );
266 if ( !fclose( $fh ) ) {
267 throw new Exception( "couldn't close $filename" );
272 * Based on an image specification, write such an image to disk, using Imagick PHP extension
273 * @param array $spec Spec describing background and circles to draw
274 * @param string $format File format to write
275 * @param string $filename Filename to write to
277 public function writeImageWithApi( $spec, $format, $filename ) {
278 // this is a hack because I can't get setImageOrientation() to work. See below.
279 global $wgExiv2Command;
281 $image = new Imagick();
283 * If the format is 'jpg', will also add a random orientation -- the
284 * image will be drawn rotated with triangle points facing in some
285 * direction (0, 90, 180 or 270 degrees) and a countering rotation
286 * should turn the triangle points upward again.
288 $orientation = self
::$orientations[0]; // default is normal orientation
289 if ( $format == 'jpg' ) {
290 $orientation = self
::$orientations[array_rand( self
::$orientations )];
291 $spec = self
::rotateImageSpec( $spec, $orientation['counterRotation'] );
294 $image->newImage( $spec['width'], $spec['height'], new ImagickPixel( $spec['fill'] ) );
296 foreach ( $spec['draws'] as $drawSpec ) {
297 $draw = new ImagickDraw();
298 $draw->setFillColor( $drawSpec['fill'] );
299 $draw->polygon( $drawSpec['shape'] );
300 $image->drawImage( $draw );
303 $image->setImageFormat( $format );
305 // this doesn't work, even though it's documented to do so...
306 // $image->setImageOrientation( $orientation['exifCode'] );
308 $image->writeImage( $filename );
310 // because the above setImageOrientation call doesn't work... nor can I
311 // get an external imagemagick binary to do this either... Hacking this
312 // for now (only works if you have exiv2 installed, a program to read
313 // and manipulate exif).
314 if ( $wgExiv2Command ) {
315 $command = Shell
::command( $wgExiv2Command,
317 "set Exif.Image.Orientation {$orientation['exifCode']}",
321 $result = $command->execute();
322 $retval = $result->getExitCode();
323 if ( $retval !== 0 ) {
324 print "Error with $command: $retval, {$result->getStdout()}\n";
330 * Given an image specification, produce rotated version
331 * This is used when simulating a rotated image capture with Exif orientation
332 * @param array $spec Returned by getImageSpec
333 * @param array $matrix 2x2 transformation matrix
334 * @return array Transformed Spec
336 private static function rotateImageSpec( &$spec, $matrix ) {
338 $dims = self
::matrixMultiply2x2( $matrix, $spec['width'], $spec['height'] );
341 if ( $dims['x'] < 0 ) {
342 $correctionX = abs( $dims['x'] );
344 if ( $dims['y'] < 0 ) {
345 $correctionY = abs( $dims['y'] );
347 $tSpec['width'] = abs( $dims['x'] );
348 $tSpec['height'] = abs( $dims['y'] );
349 $tSpec['fill'] = $spec['fill'];
350 $tSpec['draws'] = [];
351 foreach ( $spec['draws'] as $draw ) {
353 'fill' => $draw['fill'],
356 foreach ( $draw['shape'] as $point ) {
357 $tPoint = self
::matrixMultiply2x2( $matrix, $point['x'], $point['y'] );
358 $tPoint['x'] +
= $correctionX;
359 $tPoint['y'] +
= $correctionY;
360 $tDraw['shape'][] = $tPoint;
362 $tSpec['draws'][] = $tDraw;
369 * Given a matrix and a pair of images, return new position
370 * @param array $matrix 2x2 rotation matrix
371 * @param int $x The x-coordinate number
372 * @param int $y The y-coordinate number
373 * @return array Transformed with properties x, y
375 private static function matrixMultiply2x2( $matrix, $x, $y ) {
377 'x' => $x * $matrix[0][0] +
$y * $matrix[0][1],
378 'y' => $x * $matrix[1][0] +
$y * $matrix[1][1]
383 * Based on an image specification, write such an image to disk, using the
384 * command line ImageMagick program ('convert').
386 * Sample command line:
387 * $ convert -size 100x60 xc:rgb(90,87,45) \
388 * -draw 'fill rgb(12,34,56) polygon 41,39 44,57 50,57 41,39' \
389 * -draw 'fill rgb(99,123,231) circle 59,39 56,57' \
390 * -draw 'fill rgb(240,12,32) circle 50,21 50,3' filename.png
392 * @param array $spec Spec describing background and shapes to draw
393 * @param string $format File format to write (unused by this method but
394 * kept so it has the same signature as writeImageWithApi).
395 * @param string $filename Filename to write to
399 public function writeImageWithCommandLine( $spec, $format, $filename ) {
400 global $wgImageMagickConvertCommand;
403 $wgImageMagickConvertCommand,
405 $spec['width'] . 'x' . $spec['height'],
406 "xc:{$spec['fill']}",
408 foreach ( $spec['draws'] as $draw ) {
409 $fill = $draw['fill'];
410 $polygon = self
::shapePointsToString( $draw['shape'] );
411 $drawCommand = "fill $fill polygon $polygon";
413 $args[] = $drawCommand;
417 $result = Shell
::command( $args )->execute();
419 return ( $result->getExitCode() === 0 );
423 * Generate a string of random colors for ImageMagick or SVG, like "rgb(12, 37, 98)"
427 public function getRandomColor() {
429 for ( $i = 0; $i <= 2; $i++
) {
430 $components[] = mt_rand( 0, 255 );
433 return 'rgb(' . implode( ', ', $components ) . ')';
437 * Get an array of random pairs of random words, like
438 * [ [ 'foo', 'bar' ], [ 'quux', 'baz' ] ];
440 * @param int $number Number of pairs
441 * @return array Two-element arrays
443 private function getRandomWordPairs( $number ) {
444 $lines = $this->getRandomLines( $number * 2 );
445 // construct pairs of words
447 $count = count( $lines );
448 for ( $i = 0; $i < $count; $i +
= 2 ) {
449 $pairs[] = [ $lines[$i], $lines[$i +
1] ];
456 * Return N random lines from a file
458 * Will throw exception if the file could not be read or if it had fewer lines than requested.
460 * @param int $number_desired Number of lines desired
463 * @return array Array of exactly n elements, drawn randomly from lines the file
465 private function getRandomLines( $number_desired ) {
466 $filepath = $this->dictionaryFile
;
468 // initialize array of lines
470 for ( $i = 0; $i < $number_desired; $i++
) {
475 * This algorithm obtains N random lines from a file in one single pass.
476 * It does this by replacing elements of a fixed-size array of lines,
477 * less and less frequently as it reads the file.
479 $fh = fopen( $filepath, "r" );
481 throw new Exception( "couldn't open $filepath" );
484 $max_index = $number_desired - 1;
485 while ( !feof( $fh ) ) {
486 $line = fgets( $fh );
487 if ( $line !== false ) {
489 $line = trim( $line );
490 if ( mt_rand( 0, $line_number ) <= $max_index ) {
491 $lines[mt_rand( 0, $max_index )] = $line;
496 if ( $line_number < $number_desired ) {
497 throw new Exception( "not enough lines in $filepath" );