php 关于图片获取宽高的优化

码农天地 -
php 关于图片获取宽高的优化
需求
1. 应前端需求,在进入文章详情时需要将所有图片进行占位替换,且占位符需要对应图片信息(主要需要知道宽高)
2. 目的:做点击图片浮窗效果
实现方案
1. 优化前
    1.1 正则匹配图片,然后循环获取每张图片的宽高
    1.2 问题:如果文章图片较少,以上操作问题不大。但图片一旦过慢,这个效率将会非常低下
    1.3 代码如下:
        preg_match_all('/<img.*? src="(.*?)".*?>/is', $str, $matchs);
       
        if(!empty($matchs[0])){
            $pics = [];
            $i = 0;
            foreach ($matchs[0] as $key => $m) {
                $fileInfo = file_get_contents($matchs[1][$key] . '?x-oss-process=image/info');
                $fileInfo = json_decode($fileInfo, true);
                $data['Width'] = $fileInfo['ImageWidth']['value'];
                $data['Height'] = $fileInfo['ImageHeight']['value'];
                    
                $imgs[$i]['ref'] = '<!--IMG#' . $key . '-->';
                $imgs[$i]['pixel'] = $data['Width'] . '*' . $data['Height'];
                preg_match('/alt="(.*?)"/i', $matchs[0][$key], $mt);
                $imgs[$i]['alt'] = isset($mt[1]) ? $mt[1] : '';   //图片alt
                $imgs[$i]['src'] = $matchs[1][$key];                //图片地址
                $str = str_replace($m, '<!--IMG#' . $key . '-->', $str);
                $i++;

            }
        }
2. 优化思路
    2.1 想着是否会有极速获取图片法子?在网上找了一些资料,基本上都是通过读取图片部分文件信息,不需要下载/读取整个图片。找了一个类库:[https://github.com/tommoor/fastimage](https://github.com/tommoor/fastimage),试了一下。 相比以前的思路(完整的下载图片) 确实有性能上的提升。有兴趣的朋友可以试试,如果针对单张图片的信息获取,这个还是很推荐的。但批量的实现似乎还达不到目的
    2.2 分析以上操作,其实慢的过程应该还是停留在循环获取图片资源上。那么换个思路,我批量获取图片是否就ok了?上代码
    
preg_match_all('/<img.*? src="(.*?)".*?>/is', $str, $matchs);

if(!empty($matchs[0])){
    //$time = microtime(true);
    //echo  '  ---- start ' . PHP_EOL;

    foreach ($matchs[0] as $key => $m) {
        $urls[] = $matchs[1][$key] . '?x-oss-process=image/info';
    }
    $imageInfos = batchCurl($urls);

    $i = 0;
    foreach ($matchs[0] as $key => $m) {
        $image = json_decode($imageInfos[$key], true);
        $_img['Width'] = $width= $image['ImageWidth']['value'];
        $_img['Height'] = $height = $image['ImageHeight']['value'];

        $imgs[$i]['ref'] = '<!--IMG#' . $key . '-->';
        $imgs[$i]['pixel'] = $_img['Width'] . '*' . $_img['Height'];
        preg_match('/alt="(.*?)"/i', $matchs[0][$key], $mt);
        $imgs[$i]['alt'] = isset($mt[1]) ? $mt[1] : '';   //图片alt
        $imgs[$i]['src'] = $matchs[1][$key];                //图片地址
        $str = str_replace($m, '<!--IMG#' . $key . '-->', $str);

        $i++;
    }
    //echo  " ---- end  px in " . (microtime(true)-$time) . " seconds \n";
    //exit;
}
        
function batchCurl($urls)
{
    $res = $conn = [];

    // 创建批处理cURL句柄
    $mh = curl_multi_init();

    foreach ($urls as $i => $url) {
        // 创建一对cURL资源
        $conn[$i] = curl_init();
        // 设置URL和相应的选项
        curl_setopt($conn[$i], CURLOPT_URL, $url);
        curl_setopt($conn[$i], CURLOPT_HEADER, 0);
        curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($conn[$i], CURLOPT_TIMEOUT, 10);
        // 302跳转
        curl_setopt($conn[$i], CURLOPT_FOLLOWLOCATION, 1);
        // 增加句柄
        curl_multi_add_handle($mh, $conn[$i]);
    }
    $active = null;
    //防卡死写法:执行批处理句柄
    do {
        $mrc = curl_multi_exec($mh, $active);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);

    while ($active && $mrc == CURLM_OK) {
        if (curl_multi_select($mh) != -1) {
            do {
                $mrc = curl_multi_exec($mh, $active);
            } while ($mrc == CURLM_CALL_MULTI_PERFORM);
        }
    }
    foreach ($urls as $i => $url) {
        //获取当前解析的cURL的相关传输信息
        $info = curl_multi_info_read($mh);
        //获取请求头信息
        $heards = curl_getinfo($conn[$i]);
        //获取输出的文本流
        $res[$i] = curl_multi_getcontent($conn[$i]);
        // 移除curl批处理句柄资源中的某个句柄资源
        curl_multi_remove_handle($mh, $conn[$i]);
        //关闭cURL会话
        curl_close($conn[$i]);
    }
    //关闭全部句柄
    curl_multi_close($mh);

    return $res;
}
3. 测试性能,20张图片的效率几乎能达到秒级
![image](/img/bVcKCF2)
总结
1. 优化的思路很重要,重点在于分析所提所在,对症下药。在此记个笔记
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

php介绍

PHP即“超文本预处理器”,是一种通用开源脚本语言。PHP是在服务器端执行的脚本语言,与C语言类似,是常用的网站编程语言。PHP独特的语法混合了C、Java、Perl以及 PHP 自创的语法。利于学习,使用广泛,主要适用于Web开发领域。

Tags 标签

php

扩展阅读

加个好友,技术交流

1628738909466805.jpg