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

Linda Hamilton
Release: 2024-10-30 16:47:25
Original
991 people have browsed it

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:

<code class="php">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;
}</code>
Copy after login

Extracting Image Size

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

<code class="php">$im = imagecreatefromstring($raw);
$width = imagesx($im);
$height = imagesy($im);</code>
Copy after login

Performance Measurement

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

<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

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.

The above is the detailed content of How to Speed Up Image Size Retrieval in PHP: Is file_get_contents the Solution?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!