[PHP] php远程图片本地化 远程下载 →→→→→进入此内容的聊天室

来自 , 2020-08-11, 写在 PHP, 查看 103 次.
URL http://www.code666.cn/view/17eb7ecc
  1. /**
  2. * 下载远程图片到本地
  3. *
  4. * @param string $txt 用户输入的文字,可能包含有图片的url
  5. * @param string $keywords 网站域名关键字,路径中含有这个关键字的图片(即本网站图片)跳过
  6. * @return string
  7. */
  8. public function getImageToLocal($txt,$keywords = 'xxx.com')
  9. {
  10.  
  11. $matches = array();
  12. preg_match_all('/<img.+?src=(.+?)\s/is',$txt,$matches);
  13. if(!is_array($matches)) return $txt;
  14. $curl = new curl();
  15. $curl -> setHeader(true);
  16. foreach ($matches[1] as $k => $v)
  17. {
  18. $url = trim($v,"\"'");
  19. $ext = '';
  20. if(strpos($url,$keywords) === false && substr($url,0,7) == 'http://') //非本站地址,需要下载图片
  21. {
  22. $curl -> setUrl($url);
  23. $curl -> setTimeout(5);
  24. $data = $curl -> send();
  25. list($header,$imageData) = explode("\n\n",$data);
  26. if($ext = $this -> getImageExtension($header))
  27. {
  28. $file = IMAGE_SAVE_DIR . date('YmdHis') . rand(1,100) . $k . '.' . $ext;
  29. @file_put_contents($file,$imageData);
  30. if(is_file($file)) $txt = str_replace($v,'"' . str_replace(ROOT,'',$file) . '"',$txt);
  31. }
  32. }
  33. }
  34. return $txt;
  35. }
  36.  
  37. /**
  38. * 从HTTP头分离出图片的扩展名
  39. *
  40. * @param string $header HTTP头
  41. * @return string
  42. */
  43. function getImageExtension($header)
  44. {
  45. $arr = explode("\n",$header);
  46. foreach($arr as $k => $v)
  47. {
  48. $line = explode(':',$v);
  49. if($line[0] == 'Content-Type') return str_replace('image/','',trim($line[1]));
  50. }
  51. return '';
  52. }

回复 "php远程图片本地化 远程下载"

这儿你可以回复上面这条便签

captcha