PHP 抓取網頁圖片並且另存新檔的實現代碼

來源:互聯網
上載者:User

下面是原始碼,及其相關解釋 複製代碼 代碼如下:<?php
//URL是遠端完整圖片地址,不可為空, $filename 是另存新檔的圖片名字
//預設把圖片放在以此指令碼相同的目錄裡
function GrabImage($url, $filename=""){
//$url 為空白則返回 false;
if($url == ""){return false;}
$ext = strrchr($url, ".");//得到圖片的副檔名
if($ext != ".gif" && $ext != ".jpg" && $ext != ".bmp"){echo "格式不支援!";return false;}
if($filename == ""){$filename = time()."$ext";}//以時間戳記另起名
//開始捕捉
ob_start();
readfile($url);
$img = ob_get_contents();
ob_end_clean();
$size = strlen($img);
$fp2 = fopen($filename , "a");
fwrite($fp2, $img);
fclose($fp2);
return $filename;
}
//測試
GrabImage("http://www.jb51.net/images/logo.gif", "as.gif");
?>

ob_start : 開啟輸出緩衝
This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer. (輸出是在內部緩衝儲存)
//
readfile : 讀入一個檔案並寫入到輸出緩衝
返回從檔案中讀入的位元組數。如果出錯返回 FALSE 並且除非是以 @readfile() 形式調用,否則會顯示錯誤資訊。
//

ob_get_contents : Return the contents of the output buffer(返回輸出緩衝的內容)
This will return the contents of the output buffer without clearing it or FALSE, if output buffering isn't active. (如果輸出緩衝沒有活動(開啟),則返回 FALSE)
//
ob_end_clean() : Clean (erase) the output buffer and turn off output buffering(清除輸出緩衝)
This function discards(丟棄) the contents of the topmost output buffer and turns off this output buffering.(丟棄並且關掉) If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_clean() as the buffer contents are discarded when ob_end_clean() is called. (如果要用緩衝內容,則在清理輸出緩衝之前要先調用 ob_get_contents())The function returns TRUE when it successfully discarded one buffer and FALSE otherwise. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.