"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Speed Up Image Size Retrieval in PHP: Is file_get_contents the Solution?

How to Speed Up Image Size Retrieval in PHP: Is file_get_contents the Solution?

Published on 2024-11-05
Browse:941

How to Speed Up Image Size Retrieval in PHP: Is file_get_contents the Solution?

How to Obtain Image Size Lightning Fast in PHP Using file_get_contents

Getting image dimensions for numerous remote images can be a time-consuming task, especially using getimagesize. Here's an alternative approach that leverages file_get_contents to swiftly retrieve image sizes:

Using a Custom PHP Function

The following ranger() function reads a specific byte range from a remote image, enabling quick size extraction:

function ranger($url){
    $headers = array(
    "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;
}

Extracting Image Size

Once the image data is obtained, you can determine its dimensions using imagecreatefromstring() and built-in image analysis functions:

$im = imagecreatefromstring($raw);
$width = imagesx($im);
$height = imagesy($im);

Performance Measurement

Using this method, the process of obtaining image dimensions is significantly faster:

$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)";

Test Results

The example image took only 0.20859 seconds to retrieve its dimensions. Loading 32KB of data has proven effective in this approach. By applying this technique, you can swiftly obtain image sizes of remote images, minimizing the bottlenecks typically encountered with getimagesize.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3