如何高效地从尺寸大于等于200px的URL获取图片
追求打造类似Pinterest的功能“添加 Pin 图”时出现的问题是如何快速检索指定 URL 中宽度和高度大于或等于 200 像素的所有图像。虽然提供的代码需要 48.64 秒来完成该过程,但可以通过以下优化显着加速:
<code class="php">// PHP script using curl_multi_init for parallel image retrieval require 'simple_html_dom.php'; $url = 'http://www.huffingtonpost.com/'; $html = file_get_html ( $url ); $nodes = array (); $start = microtime (); $res = array (); if ($html->find ( 'img' )) { foreach ( $html->find ( 'img' ) as $element ) { if (startsWith ( $element->src, "/" )) { $element->src = $url . $element->src; } if (! startsWith ( $element->src, "http" )) { $element->src = $url . "/" . $element->src; } $nodes [] = $element->src; } } echo "<pre class="brush:php;toolbar:false">"; print_r ( imageDownload ( $nodes, 200, 200 ) ); echo "<h1>", microtime () - $start, "</h1>"; function imageDownload($nodes, $maxHeight = 0, $maxWidth = 0) { $mh = curl_multi_init (); $curl_array = array (); foreach ( $nodes as $i => $url ) { $curl_array [$i] = curl_init ( $url ); curl_setopt ( $curl_array [$i], CURLOPT_RETURNTRANSFER, true ); curl_setopt ( $curl_array [$i], CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)' ); curl_setopt ( $curl_array [$i], CURLOPT_CONNECTTIMEOUT, 5 ); curl_setopt ( $curl_array [$i], CURLOPT_TIMEOUT, 15 ); curl_multi_add_handle ( $mh, $curl_array [$i] ); } $running = NULL; do { usleep ( 10000 ); curl_multi_exec ( $mh, $running ); } while ( $running > 0 ); $res = array (); foreach ( $nodes as $i => $url ) { $curlErrorCode = curl_errno ( $curl_array [$i] ); if ($curlErrorCode === 0) { $info = curl_getinfo ( $curl_array [$i] ); $ext = getExtention ( $info ['content_type'] ); if ($info ['content_type'] !== null) { $temp = "temp/img" . md5 ( mt_rand () ) . $ext; touch ( $temp ); $imageContent = curl_multi_getcontent ( $curl_array [$i] ); file_put_contents ( $temp, $imageContent ); if ($maxHeight == 0 || $maxWidth == 0) { $res [] = $temp; } else { $size = getimagesize ( $temp ); if ($size [1] >= $maxHeight && $size [0] >= $maxWidth) { $res [] = $temp; } else { unlink ( $temp ); } } } } curl_multi_remove_handle ( $mh, $curl_array [$i] ); curl_close ( $curl_array [$i] ); } curl_multi_close ( $mh ); return $res; } function getExtention($type) { $type = strtolower ( $type ); switch ($type) { case "image/gif" : return ".gif"; break; case "image/png" : return ".png"; break; case "image/jpeg" : return ".jpg"; break; default : return ".img"; break; } } function startsWith($str, $prefix) { $temp = substr ( $str, 0, strlen ( $prefix ) ); $temp = strtolower ( $temp ); $prefix = strtolower ( $prefix ); return ($temp == $prefix); }</code>
以上是如何高效地从URL中检索尺寸大于或等于200px的图片?的详细内容。更多信息请关注PHP中文网其他相关文章!