首頁  >  文章  >  後端開發  >  gd庫圖片下載類別實作下載網頁所有圖片的php程式碼

gd庫圖片下載類別實作下載網頁所有圖片的php程式碼

高洛峰
高洛峰原創
2016-12-01 10:34:531090瀏覽

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); 
//符合字串$content,將所有符合字串儲存到陣列$mat reg = "/gd庫圖片下載類別實作下載網頁所有圖片的php程式碼/i"; 
preg_match_all($reg, $content, $matches); 
$count = count($matches[0] ); 
for ($i=0; $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 
); $i=0; $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; //設定圖片! 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'; 
; quality) ? $this->quality : 100; 
break; 
case 'png': 
$img_create_func = 'imagecreatefrompng'; 
$img_save_func = 'imagecreatefrompng'; 
case ' bmp': 
$img_create_func = 'imagecreatefrombmp'; 
$img_save_func = 'imagebmp'; 
$new_img_ext = 'bmp'; 
breakf5;
$img_save_func = 'imagegif '; 
$new_img_ext = 'gif'; 
break; 
case 'vnd.wap.wbmp': 
$img_create_func = 'imagecreatefromwbmp';
break;
case 'xbm': 
$img_create_func = 'imagecreatefromxbm'; 
$img_save_func = 'imagexbm'; 
$new_img_ext = 'xbm'break ); fromjpeg'; 
$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->); if (isset($image_quality)){ 
$save_img = @$img_save_func($img,$save_address,$image_quality); 
}else{ 
$save_img = @$img_s_op $save_img; 

} 🎜?> 

 
遠端url位址: 
 
 

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:java讀取檔名下一篇:java讀取檔名