代码改变世界

转:php 保存远程图片到本地

  youxin  阅读(777)  评论(0编辑  收藏  举报

显示远程图片:

  1. <?php    
  2. header('Content-Type:image/jpg');    
  3. echo file_get_contents("http://www.baidu.com/img/baidu_logo.gif");    
  4. ?>  

 

第一种: 精确型

复制代码
<?php   
  
// 变量说明:   
// $url 是远程图片的完整URL地址,不能为空。  
// $filename 是可选变量: 如果为空,本地文件名将基于时间和日期   
// 自动生成.   
  
function get_photo($url,$filename='',$savefile='test/') 
{   
    $imgArr = array('gif','bmp','png','ico','jpg','jepg');

    if(!$url) return false;
  
    if(!$filename) {   
      $ext=strtolower(end(explode('.',$url)));   
      if(!in_array($ext,$imgArr)) return false;
      $filename=date("dMYHis").'.'.$ext;   
    }   

    if(!is_dir($savefile)) mkdir($savefile, 0777);
    if(!is_readable($savefile)) chmod($savefile, 0777);
    
    $filename = $savefile.$filename;

    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;   
 }   
 

 $img=get_photo("http://www.baidu.com/img/baidu_logo.gif");   
 echo $img ? '<pre><img src="'.$img.'"></pre>' : "false";
复制代码

第二种:从文章中提取图片,并保存至本地

复制代码
function getImg($str){
    $str = stripslashes($str);
    $pattern = "/<img[^>]*src\=\"(([^>]*)(jpg|gif|png|bmp|jpeg))\"/i";   //获取所有图片标签的全部信息
    preg_match_all($pattern, $str, $matches);
      
    return $matches[1];   //$matches[1]中就是所想匹配的结果,结果为数组
}

    $str = <<<EOT
Money has been moving into Brazilian stocks over the last couple of days, despite mostly flat trading activity in the U.S. equity markets. During Thursday's session, the iShares MSCI Brazil Index ETF (NYSE: EWZ) has risen 1.12% after outperforming the U.S. indices yesterday as well.

Must Read
SonySony Playstation Phone Rumors Heat Up
A South Korean Army soldier walks up steps of a guard post near the demilitarised zone separating the two Koreas.S. Korea waves olive branch
<img width="1" height="1" alt="" src="http://img.ibtimes.com/www/site/us/images/1px.gif" sized="yes">
Two giant resource companies make up a big chunk of the Brazilian Bovespa. They are PetroBras (NYSE: PBR), with a market cap of $163.44 billion, and miner Vale (NYSE: VALE), which has a market cap of $178.95 billion. PBR shares have risen 1.47% thus far today and VALE is trading 0.77% higher at $34.03.
<img alt="Sony" src="http://img.ibtimes.com/www/thumb/mainpage/13463-12079-sony.jpg" sized="yes">
This article was originally published on Benzinga, and is republished here with permission. 
EOT;


foreach( getImg($str) as $url)
{
    get_photo($url);
}
复制代码

 

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示