3 namespace Faker\Provider;
6 * Depends on image generation from http://lorempixel.com/
8 class Image extends Base
10 protected static $categories = array(
11 'abstract', 'animals', 'business', 'cats', 'city', 'food', 'nightlife',
12 'fashion', 'people', 'nature', 'sports', 'technics', 'transport'
16 * Generate the URL that will return a random image
18 * Set randomize to false to remove the random GET parameter at the end of the url.
20 * @example 'http://lorempixel.com/640/480/?12345'
22 * @param integer $width
23 * @param integer $height
24 * @param string|null $category
25 * @param bool $randomize
26 * @param string|null $word
31 public static function imageUrl($width = 640, $height = 480, $category = null, $randomize = true, $word = null, $gray = false)
33 $baseUrl = "https://lorempixel.com/";
34 $url = "{$width}/{$height}/";
37 $url = "gray/" . $url;
41 if (!in_array($category, static::$categories)) {
42 throw new \InvalidArgumentException(sprintf('Unknown image category "%s"', $category));
44 $url .= "{$category}/";
51 $url .= '?' . static::randomNumber(5, true);
54 return $baseUrl . $url;
58 * Download a remote random image to disk and return its location
60 * Requires curl, or allow_url_fopen to be on in php.ini.
62 * @example '/path/to/dir/13b73edae8443990be1aa8f1a483bc27.jpg'
64 public static function image($dir = null, $width = 640, $height = 480, $category = null, $fullPath = true, $randomize = true, $word = null, $gray = false)
66 $dir = is_null($dir) ? sys_get_temp_dir() : $dir; // GNU/Linux / OS X / Windows compatible
67 // Validate directory path
68 if (!is_dir($dir) || !is_writable($dir)) {
69 throw new \InvalidArgumentException(sprintf('Cannot write to directory "%s"', $dir));
72 // Generate a random filename. Use the server address so that a file
73 // generated at the same time on a different server won't have a collision.
74 $name = md5(uniqid(empty($_SERVER['SERVER_ADDR']) ? '' : $_SERVER['SERVER_ADDR'], true));
75 $filename = $name .'.jpg';
76 $filepath = $dir . DIRECTORY_SEPARATOR . $filename;
78 $url = static::imageUrl($width, $height, $category, $randomize, $word, $gray);
81 if (function_exists('curl_exec')) {
83 $fp = fopen($filepath, 'w');
84 $ch = curl_init($url);
85 curl_setopt($ch, CURLOPT_FILE, $fp);
86 $success = curl_exec($ch) && curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200;
93 // could not contact the distant URL or HTTP error - fail silently.
96 } elseif (ini_get('allow_url_fopen')) {
97 // use remote fopen() via copy()
98 $success = copy($url, $filepath);
100 return new \RuntimeException('The image formatter downloads an image from a remote HTTP server. Therefore, it requires that PHP can request remote hosts, either via cURL or fopen()');
103 return $fullPath ? $filepath : $filename;