php:批量将文章内容中的图片替换为Base64格式

最近在为一国企的老旧项目做改造,由于对方发布端在内网,展示端在外网。需要在发布时进行内容同步,为了方便起见就想到了把内容中的图片全部转换成Base64,POST发送至外网服务器后,再全部转换成图片文件保存在外网服务器中。

贴一个批量将文章内容中的图片替换为Base64格式的代码片段,以便后期方便查找。

  1. /**
  2.  * 转换新闻发布中出现的图片
  3.  */
  4. function transNewsParam($param){
  5.     $host = app()->getRootPath()."public";
  6.     $img_file = $host.$param['img'];
  7.     $param['img'] = imgToBase64(str_replace("/",DIRECTORY_SEPARATOR,$img_file));
  8.     $param['content'] = transNewsContent(html_entity_decode($param['content']));
  9.     return $param;
  10. }
  11. function transNewsContent($content){
  12.     $pregRule = "/(<[img|IMG].*?src=[\'|\"])(.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))([\'|\"].*?[\/]?>)/";
  13.     $host = app()->getRootPath()."public";
  14.     $result = preg_replace_callback($pregRulefunction ($matchuse($host){
  15.         # 处理src
  16.         return $match[1].imgToBase64($host.str_replace("/",DIRECTORY_SEPARATOR,$match[2])).$match[3];
  17.     },$content);
  18.     return $result;
  19. }
  20. function imgToBase64($img_file) {
  21.     $img_base64 = '';
  22.     if (file_exists($img_file)) {
  23.         $img_info = getimagesize($img_file); // 取得图片的大小,类型等
  24.         $fp = fopen($img_file"r"); // 图片是否可读权限
  25.         if ($fp) {
  26.             $filesize = filesize($img_file);
  27.             $content = fread($fp$filesize);
  28.             $file_content = chunk_split(base64_encode($content)); // base64编码
  29.             switch ($img_info[2]) {           //判读图片类型
  30.                 case 1: $img_type = "gif";
  31.                     break;
  32.                 case 2: $img_type = "jpg";
  33.                     break;
  34.                 case 3: $img_type = "png";
  35.                     break;
  36.             }
  37.             $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码
  38.         }
  39.         fclose($fp);
  40.     }
  41.     return $img_base64;
  42. }

注意:

1、上述涉及图片地址为相对路径,读取时需转换绝对路径。能读取到图像文件方能转换。

2、以上代码部分函数基于Thinkphp6,应用在其他地方时需要自行修改。

 

你想把广告放到这里吗?

发表评论

您必须 登录 才能发表留言!