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 circles)
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 $circlesToDraw = 5;
35 private $imageWriteMethod;
37 public function __construct( $options = array() ) {
38 foreach ( array( 'dictionaryFile', 'minWidth', 'minHeight', 'maxHeight', 'circlesToDraw' ) as $property ) {
39 if ( isset( $options[$property] ) ) {
40 $this->$property = $options[$property];
44 // find the dictionary file, to generate random names
45 if ( !isset( $this->dictionaryFile
) ) {
46 foreach ( array( '/usr/share/dict/words', '/usr/dict/words' ) as $dictionaryFile ) {
47 if ( is_file( $dictionaryFile ) and is_readable( $dictionaryFile ) ) {
48 $this->dictionaryFile
= $dictionaryFile;
53 if ( !isset( $this->dictionaryFile
) ) {
54 throw new Exception( "RandomImageGenerator: dictionary file not found or not specified properly" );
59 * Writes random images with random filenames to disk in the directory you specify, or current working directory
61 * @param $number Integer: number of filenames to write
62 * @param $format String: optional, must be understood by ImageMagick, such as 'jpg' or 'gif'
63 * @param $dir String: directory, optional (will default to current working directory)
64 * @return Array: filenames we just wrote
66 function writeImages( $number, $format = 'jpg', $dir = null ) {
67 $filenames = $this->getRandomFilenames( $number, $format, $dir );
68 $imageWriteMethod = $this->getImageWriteMethod( $format );
69 foreach( $filenames as $filename ) {
70 $this->{$imageWriteMethod}( $this->getImageSpec(), $format, $filename );
77 * Figure out how we write images. This is a factor of both format and the local system
78 * @param $format (a typical extension like 'svg', 'jpg', etc.)
80 function getImageWriteMethod( $format ) {
81 global $wgUseImageMagick, $wgImageMagickConvertCommand;
82 if ( $format === 'svg' ) {
85 // figure out how to write images
86 if ( class_exists( 'Imagick' ) ) {
87 return 'writeImageWithApi';
88 } elseif ( $wgUseImageMagick && $wgImageMagickConvertCommand && is_executable( $wgImageMagickConvertCommand ) ) {
89 return 'writeImageWithCommandLine';
92 throw new Exception( "RandomImageGenerator: could not find a suitable method to write images in '$format' format" );
96 * Return a number of randomly-generated filenames
97 * Each filename uses two words randomly drawn from the dictionary, like elephantine_spatula.jpg
99 * @param $number Integer: of filenames to generate
100 * @param $extension String: optional, defaults to 'jpg'
101 * @param $dir String: optional, defaults to current working directory
102 * @return Array: of filenames
104 private function getRandomFilenames( $number, $extension = 'jpg', $dir = null ) {
105 if ( is_null( $dir ) ) {
108 $filenames = array();
109 foreach( $this->getRandomWordPairs( $number ) as $pair ) {
110 $basename = $pair[0] . '_' . $pair[1];
111 if ( !is_null( $extension ) ) {
112 $basename .= '.' . $extension;
114 $basename = preg_replace( '/\s+/', '', $basename );
115 $filenames[] = "$dir/$basename";
124 * Generate data representing an image of random size (within limits),
125 * consisting of randomly colored and sized circles against a random background color
126 * (This data is used in the writeImage* methods).
129 public function getImageSpec() {
132 $spec['width'] = mt_rand( $this->minWidth
, $this->maxWidth
);
133 $spec['height'] = mt_rand( $this->minHeight
, $this->maxHeight
);
134 $spec['fill'] = $this->getRandomColor();
136 $diagonalLength = sqrt( pow( $spec['width'], 2 ) +
pow( $spec['height'], 2 ) );
139 for ( $i = 0; $i <= $this->circlesToDraw
; $i++
) {
140 $radius = mt_rand( 0, $diagonalLength / 4 );
141 $originX = mt_rand( -1 * $radius, $spec['width'] +
$radius );
142 $originY = mt_rand( -1 * $radius, $spec['height'] +
$radius );
143 $perimeterX = $originX +
$radius;
144 $perimeterY = $originY +
$radius;
147 $draw['fill'] = $this->getRandomColor();
148 $draw['circle'] = array(
149 'originX' => $originX,
150 'originY' => $originY,
152 'perimeterX' => $perimeterX,
153 'perimeterY' => $perimeterY
159 $spec['draws'] = $draws;
166 * Based on image specification, write a very simple SVG file to disk.
167 * Ignores the background spec because transparency is cool. :)
168 * @param $spec: spec describing background and circles to draw
169 * @param $format: file format to write (which is obviously always svg here)
170 * @param $filename: filename to write to
172 public function writeSvg( $spec, $format, $filename ) {
173 $svg = new SimpleXmlElement( '<svg/>' );
174 $svg->addAttribute( 'xmlns', 'http://www.w3.org/2000/svg' );
175 $svg->addAttribute( 'version', '1.1' );
176 $svg->addAttribute( 'width', $spec['width'] );
177 $svg->addAttribute( 'height', $spec['height'] );
178 $g = $svg->addChild( 'g' );
179 foreach ( $spec['draws'] as $drawSpec ) {
180 $circle = $g->addChild( 'circle' );
181 $circle->addAttribute( 'fill', $drawSpec['fill'] );
182 $circleSpec = $drawSpec['circle'];
183 $circle->addAttribute( 'cx', $circleSpec['originX'] );
184 $circle->addAttribute( 'cy', $circleSpec['originY'] );
185 $circle->addAttribute( 'r', $circleSpec['radius'] );
187 if ( ! $fh = fopen( $filename, 'w' ) ) {
188 throw new Exception( "couldn't open $filename for writing" );
190 fwrite( $fh, $svg->asXML() );
191 if ( !fclose($fh) ) {
192 throw new Exception( "couldn't close $filename" );
197 * Based on an image specification, write such an image to disk, using Imagick PHP extension
198 * @param $spec: spec describing background and circles to draw
199 * @param $format: file format to write
200 * @param $filename: filename to write to
202 public function writeImageWithApi( $spec, $format, $filename ) {
203 $image = new Imagick();
204 $image->newImage( $spec['width'], $spec['height'], new ImagickPixel( $spec['fill'] ) );
206 foreach ( $spec['draws'] as $drawSpec ) {
207 $draw = new ImagickDraw();
208 $draw->setFillColor( $drawSpec['fill'] );
209 $circle = $drawSpec['circle'];
210 $draw->circle( $circle['originX'], $circle['originY'], $circle['perimeterX'], $circle['perimeterY'] );
211 $image->drawImage( $draw );
214 $image->setImageFormat( $format );
215 $image->writeImage( $filename );
220 * Based on an image specification, write such an image to disk, using the command line ImageMagick program ('convert').
222 * Sample command line:
223 * $ convert -size 100x60 xc:rgb(90,87,45) \
224 * -draw 'fill rgb(12,34,56) circle 41,39 44,57' \
225 * -draw 'fill rgb(99,123,231) circle 59,39 56,57' \
226 * -draw 'fill rgb(240,12,32) circle 50,21 50,3' filename.png
228 * @param $spec: spec describing background and circles to draw
229 * @param $format: file format to write (unused by this method but kept so it has the same signature as writeImageWithApi)
230 * @param $filename: filename to write to
232 public function writeImageWithCommandLine( $spec, $format, $filename ) {
233 global $wgImageMagickConvertCommand;
235 $args[] = "-size " . wfEscapeShellArg( $spec['width'] . 'x' . $spec['height'] );
236 $args[] = wfEscapeShellArg( "xc:" . $spec['fill'] );
237 foreach( $spec['draws'] as $draw ) {
238 $fill = $draw['fill'];
239 $originX = $draw['circle']['originX'];
240 $originY = $draw['circle']['originY'];
241 $perimeterX = $draw['circle']['perimeterX'];
242 $perimeterY = $draw['circle']['perimeterY'];
243 $drawCommand = "fill $fill circle $originX,$originY $perimeterX,$perimeterY";
244 $args[] = '-draw ' . wfEscapeShellArg( $drawCommand );
246 $args[] = wfEscapeShellArg( $filename );
248 $command = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " . implode( " ", $args );
250 wfShellExec( $command, $retval );
251 return ( $retval === 0 );
255 * Generate a string of random colors for ImageMagick or SVG, like "rgb(12, 37, 98)"
259 public function getRandomColor() {
260 $components = array();
261 for ($i = 0; $i <= 2; $i++
) {
262 $components[] = mt_rand( 0, 255 );
264 return 'rgb(' . join(', ', $components) . ')';
268 * Get an array of random pairs of random words, like array( array( 'foo', 'bar' ), array( 'quux', 'baz' ) );
270 * @param $number Integer: number of pairs
271 * @return Array: of two-element arrays
273 private function getRandomWordPairs( $number ) {
274 $lines = $this->getRandomLines( $number * 2 );
275 // construct pairs of words
277 $count = count( $lines );
278 for( $i = 0; $i < $count; $i +
= 2 ) {
279 $pairs[] = array( $lines[$i], $lines[$i+
1] );
286 * Return N random lines from a file
288 * Will throw exception if the file could not be read or if it had fewer lines than requested.
290 * @param $number_desired Integer: number of lines desired
291 * @return Array: of exactly n elements, drawn randomly from lines the file
293 private function getRandomLines( $number_desired ) {
294 $filepath = $this->dictionaryFile
;
296 // initialize array of lines
298 for ( $i = 0; $i < $number_desired; $i++
) {
303 * This algorithm obtains N random lines from a file in one single pass. It does this by replacing elements of
304 * a fixed-size array of lines, less and less frequently as it reads the file.
306 $fh = fopen( $filepath, "r" );
308 throw new Exception( "couldn't open $filepath" );
311 $max_index = $number_desired - 1;
312 while( !feof( $fh ) ) {
313 $line = fgets( $fh );
314 if ( $line !== false ) {
316 $line = trim( $line );
317 if ( mt_rand( 0, $line_number ) <= $max_index ) {
318 $lines[ mt_rand( 0, $max_index ) ] = $line;
323 if ( $line_number < $number_desired ) {
324 throw new Exception( "not enough lines in $filepath" );