本案例是存储到oss上,上传oss之前会先保存到本地目录.
最终返回路径是oss图片完整路径。
如果不需要上传oss,去掉即可。
public function replaceimg($xstr){
//保存路径
$d = date('Y-m-d', time());
$dirslsitss = TP::root_path().'/Uploads/Picture'.'/'.$d;//本地存储目录
$savePath = '/Uploads/Headline'.'/'.$d; //入库路径
if(!is_dir($dirslsitss)) {
@mkdir($dirslsitss, 0777);
}
//匹配图片的src
preg_match_all('#<img.*?src="([^"]*)"[^>]*>#i', $xstr, $match);
foreach($match[1] as $imgurl){
if(is_int(strpos($imgurl, 'http'))){
$arcurl = $imgurl;
} else {
$arcurl = 'http://'.ltrim($imgurl,'\//'); //17173,qqGame,需要拼接网址,特殊处理
}
$file = @file_get_contents($arcurl);
$imgAttr = get_headers($arcurl,true);
switch($imgAttr['Content-Type']){
case 'image/png' :
$ext = 'png';
break;
case 'image/jpeg' :
$ext = 'jpg';
break;
case 'image/gif' :
$ext = 'gif';
break;
default:
$ext = 'jpg';
}
if($arcurl) {
//保存图片到服务器
$fileimgname = time().rand(1000,9999).'.'.$ext;
$filecachs=$dirslsitss.'/'.$fileimgname;
$oss_file_path ="icon/". $fileimgname;
$fanhuistr = file_put_contents( $filecachs, $file );
$saveimgfile = $savePath."/".$fileimgname;
$ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);//上传到oss中
$ossClient->uploadFile($this->bucket, $oss_file_path, $filecachs);
$to = "http://" . $this->bucket . "." . $this->endpoint . "/icon/" .$fileimgname;
$xstr=str_replace($imgurl,$to,$xstr);
}else{
$xstr = false;
}
}
return $xstr;
}
网友评论