将图片下载到服务器指定目录下,将该目录挂在一个图片域名下。编辑助手函数:
<?php
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
if (!function_exists('replaceImageUrl')) {
/**
* 替换文章内容图片地址
* @param string $content
* @return string
*/
function replaceImageUrl(string $content): string
{
//保存路径
$path = 'image/' . Date('Y-m-d') . "/assets/news/";
$dist = 'app/iptv-webservice/' .$path;
$host = env('HTTP');// 例:https://haha.xixi.org/image/
if (!File::exists(storage_path($dist))) {
File::makeDirectory(storage_path($dist), 0755, true, true);
}
preg_match_all('#<img.*?src="([^"]*)"[^>]*>#i', $content, $match);
foreach($match[1] as $imgurl){
$img=file_get_contents($imgurl);
if(!empty($img)) {
$filename = explode('.', $imgurl);
$tmpFilename = $filename;
$imageType = array_pop($tmpFilename);
$tmpImage = implode('.', $tmpFilename);
$relativePathToFile = $path.md5($tmpImage).'.'.$imageType;
Storage::put($relativePathToFile, Image::make($imgurl)->encode($imageType));
$savePath = $host . $relativePathToFile;
$content = str_replace($imgurl,$savePath,$content);
}
}
return $content;
}
}