search
HomeBackend DevelopmentPHP TutorialUse the gd library in php to download all images in the web page, _PHP tutorial

The gd library is used in php to download all the pictures in the web page.

In the early php tutorial, it was mentioned that the php gd library can realize the download of remote pictures, but that is just downloading The principle is the same for a picture. If you want to download all the pictures of a web page, you only need to use regular expressions to judge. Find all the picture URLs and then download them in a loop. I specially wrote the gd library picture download class with reference to network resources. !
The php code is as follows:

<&#63;php
header("Content-type:text/html ; charset=utf-8");
if (!empty($_POST['submit'])){
 $url = $_POST['url'];
 //为了获取相对路径的图片所做的操作
 $url_fields = parse_url($url);
 $main_url = $url_fields['host'];
 $base_url = substr($url,0,strrpos($url, '/')+1);
 //获取网页内容
 //设置代理服务器
 $opts = array('http'=>array('request_fulluri'=>true));
 $context = stream_context_create($opts);
 $content = file_get_contents($url,false,$context);
 //匹配img标签,将所有匹配字符串保存到数组$matches
 $reg = "/<img  src="/static/imghwm/default1.png"  data-src="http://www.bkjia.com/uploads/allimg/150513/222Q559A-0.jpg?201541210942?x-oss-process=image/resize,p_40"  class="lazy" .*&#63;src=\"(.*&#63;)\".*&#63; alt="Use the gd library in php to download all images in the web page, _PHP tutorial" >/i";
 preg_match_all($reg, $content, $matches);
 $count = count($matches[0]);
 for ($i=0; $i<$count; $i++){
 /*将所有图片的url转换为小写
  *$matches[1][$i] = strtolower($matches[1][$i]);
 */
 //如果图片为相对路径就转化为全路径
 if (!strpos('a'.$matches[1][$i], 'http')){
  //因为'/'是第0个位置
  if (strpos('a'.$matches[1][$i], '/')){
  $matches[1][$i] = 'http://'.$main_url.$matches[1][$i];
  }else{
  $matches[1][$i] = $base_url.$matches[1][$i];
  }
 }
 }
 //过滤重复的图片
 $img_arr = array_unique($matches[1]);
 //实例化图片下载类
 $getImg = new DownImage();
 $url_count = count($img_arr);
 for ($i=0; $i<$url_count; $i++){
 $getImg->source = $img_arr[$i];
 $getImg->save_address = './pic/';
 $file = $getImg->download();
 }
 echo "下载完成!哈哈,简单吧!";
}
class DownImage{
 public $source;//远程图片URL
 public $save_address;//保存本地地址
 public $set_extension; //设置图片扩展名
 public $quality; //图片的质量(0~100,100最佳,默认75左右)
 //下载方法(选用GD库图片下载)
 public function download(){
 //获取远程图片信息
 $info = @getimagesize($this->source);
 //获取图片扩展名
 $mime = $info['mime'];
 $type = substr(strrchr($mime, '/'), 1);
 //不同的图片类型选择不同的图片生成和保存函数
 switch($type){
  case 'jpeg':
  $img_create_func = 'imagecreatefromjpeg';
  $img_save_func = 'imagejpeg';
  $new_img_ext = 'jpg';
  $image_quality = isset($this->quality) &#63; $this->quality : 100;
  break;
  case 'png':
  $img_create_func = 'imagecreatefrompng';
  $img_save_func = 'imagepng';
  $new_img_ext = 'png';
  break;
  case 'bmp':
  $img_create_func = 'imagecreatefrombmp';
  $img_save_func = 'imagebmp';
  $new_img_ext = 'bmp';
  break;
  case 'gif':
  $img_create_func = 'imagecreatefromgif';
  $img_save_func = 'imagegif';
  $new_img_ext = 'gif';
  break;
  case 'vnd.wap.wbmp':
  $img_create_func = 'imagecreatefromwbmp';
  $img_save_func = 'imagewbmp';
  $new_img_ext = 'bmp';
  break;
  case 'xbm':
  $img_create_func = 'imagecreatefromxbm';
  $img_save_func = 'imagexbm';
  $new_img_ext = 'xbm';
  break;
  default:
  $img_create_func = 'imagecreatefromjpeg';
  $img_save_func = 'imagejpeg';
  $new_img_ext = 'jpg';
 }
 //根据是否设置扩展名来合成本地文件名
 if (isset($this->set_extension)){
  $ext = strrchr($this->source,".");
  $strlen = strlen($ext);
  $newname = basename(substr($this->source,0,-$strlen)).'.'.$new_img_ext;
 }else{
  $newname = basename($this->source);
 }
 
 //生成本地文件路径
 $save_address = $this->save_address.$newname;
 $img = @$img_create_func($this->source);
 if (isset($image_quality)){
  $save_img = @$img_save_func($img,$save_address,$image_quality);
 }else{
  $save_img = @$img_save_func($img,$save_address);
 }
 return $save_img; 
 }
}
&#63;>
<form method="POST" action="">
远程url地址:<input type="text" name="url" size=30 />
<input type="submit" name="submit" value="下载该页面所有图片" />
</form>

The running results are as shown below:

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/998564.htmlTechArticleThe gd library is used in php to download all the images in the web page. In the previous php tutorial, it was mentioned that the php gd library can Realize the download of remote pictures, but it only downloads one picture. The principle is the same...
Statement
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools