thinkphp如何实现图片本地化,只需几步!

有时候复制人家的文章携带的图片是含有别人的链接 非常不友好,所以我们需要把他保存到本地来调用 逻辑 分析逻辑 既然是本地化那必须得下载图片 然后再进行替换 我的...

有时候复制人家的文章携带的图片是含有别人的链接

非常不友好,所以我们需要把他保存到本地来调用

逻辑

分析逻辑 既然是本地化那必须得下载图片 然后再进行替换

我的代码思路

   /**
   * @content_img 图片本地化
   * @author zhaosong
   * @date 2023-8-17
   */
    public static function content_img($html,$id) {
    	// 匹配所有的图片标签
        preg_match_all('/<img[^>]+src="([^">]+)"/i', $html, $matches);
    	// 遍历每个 <img> 标签
    	foreach ($matches[1] as $image) {
    		// 判断图片链接是否以 "http://" 或 "https://" 开头
    		if (self::startsWith($image, 'http://') || self::startsWith($image, 'https://')) {
    			// 下载图片并替换链接
    			$newSrc = self::downloadAndReplaceImage($image,$id);
    			// 更新 <img> 标签的 src 属性值
    			$html = str_replace($image, $newSrc, $html);
    		}
    	}
    	// 返回替换后的 HTML 内容
    	return $html;
    }

现在内容文本中匹配然后按条件来替换

判断是不是外链接


	/**
   * @判断字符串是否以指定的内容开头
   * @author zhaosong
   * @date 2023-8-17
   */
	public static function startsWith($haystack, $needle) {
		return strncmp($haystack, $needle, strlen($needle)) === 0;
	}

然后我们需要下载图片到指定路径 然后输出图片路径进行替换更改

	/**
   * @下载图片并保存到指定的输出目录
   * @author zhaosong
   * @date 2023-8-17
   */
	public static function downloadAndReplaceImage($src,$id) {
	    $outputDirectory = app()->getrootPath().'/public/editor/'.$id;
	    // 创建文件夹
        if (!file_exists($outputDirectory)) {
            mkdir($outputDirectory, 0777, true);
        }
	    $filename = date('YmdHis') . '_' . basename($src);
	    // 拼接本地保存路径
        $localPath = $outputDirectory . '/' . $filename;
        // 下载图片并保存到本地
       file_put_contents($localPath, file_get_contents($src));
       // 返回本地图片链接
       return str_replace(app()->getrootPath().'/public', '', $localPath);
	}

当我们删除文章的时候肯定图片也不能留了

	/**
   * @当文章被删除时本地化里的图片逐一删除
   * @author zhaosong
   * @date 2023-8-17
   */
	public static function content_img_del($folder) {
		if (is_dir($folder)) {
            $files = glob($folder . '/*');
            foreach ($files as $file) {
                is_dir($file) ? self::content_img_del($file) : unlink($file);
            }
            rmdir($folder);
        }
	}

OK完美实现本地化!!!