Home > Backend Development > PHP Tutorial > How can I optimize getimagesize performance for remote images?

How can I optimize getimagesize performance for remote images?

Susan Sarandon
Release: 2024-10-29 08:06:30
Original
476 people have browsed it

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>
Copy after login

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>
Copy after login

In tests, fetching the first 32 KB of image data provided impressive performance gains:

640 x 480 (0.20859s)
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template