Home > Article > Backend Development > How can I optimize getimagesize performance for remote images?
Accelerating getimagesize Performance for Remote Images
Getimagesize is often used to determine the dimensions of remote images. However, when dealing with large numbers of images, it can become time-consuming.
A faster approach involves fetching a small portion of the image data using file_get_contents and analyzing it to retrieve the size. This method avoids the overhead of loading the entire image.
Here's an example of how to implement this technique using the ranger function:
<code class="php">function ranger($url) { $headers = ["Range: bytes=0-32768"]; $curl = curl_init($url); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $data = curl_exec($curl); curl_close($curl); return $data; }</code>
To demonstrate the improved performance, consider the following example:
<code class="php">$start = microtime(true); $url = "http://news.softpedia.com/images/news2/Debian-Turns-15-2.jpeg"; $raw = ranger($url); $im = imagecreatefromstring($raw); $width = imagesx($im); $height = imagesy($im); $stop = round(microtime(true) - $start, 5); echo $width." x ".$height." ({$stop}s)";</code>
In tests, fetching the first 32 KB of image data provided impressive performance gains:
640 x 480 (0.20859s)
This approach significantly reduces the time required to determine the size of remote images, making it ideal for processing large datasets.
The above is the detailed content of How can I optimize getimagesize performance for remote images?. For more information, please follow other related articles on the PHP Chinese website!