2 回答
TA贡献1851条经验 获得超4个赞
$content = request()->get('content');
$dom = new \DomDocument();
$dom->loadHtml($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
$imageSrc = $image->getAttribute('src');
if (preg_match('/data:image/', $imageSrc)) {
preg_match('/data:image\/(?<mime>.*?)\;/', $imageSrc, $mime);
$mimeType = $mime['mime'];
$filename = uniqid();
$filePath = "/uploads/$filename.$mimeType";
Image::make($imageSrc)
->encode($mimeType, 100)
->save(public_path($filePath));
$newImageSrc = asset($filePath);
$image->removeAttribute('src');
$image->setAttribute('src', $newImageSrc);
}
}
$newMessageBody = $dom->saveHTML();
TA贡献1805条经验 获得超10个赞
为了避免错误的 HTML 格式引发错误,请使用LIBXML_NOWARNING | LIBXML_NOERROR
检测img src中的 base64 图像的一个简单方法是检测字符串中的data:image 。虽然不是最佳方式,但可以毫无问题地解决。
最后,在summernote内容中修改img src前面的正斜杠“ / ”,即可解决从DB获取结果后summer note内容中图像不显示的问题
如果您有任何建议和最佳方法,请发表评论,我将很高兴。谢谢。 代码 (我的解决方案)
//checking if request is set
if (isset($request->long_description)) {
$detail=$request->long_description;
//Prepare HTML & ignore HTML errors
$dom = new \domdocument();
$dom->loadHtml($detail, LIBXML_NOWARNING | LIBXML_NOERROR);
//identify img element
$images = $dom->getelementsbytagname('img');
//loop over img elements, decode their base64 source data (src) and save them to folder,
//and then replace base64 src with stored image URL.
foreach($images as $k => $img){
//collect img source data
$data = $img->getattribute('src');
//checking if img source data is image by detecting 'data:image' in string
if (strpos($data, 'data:image')!==false){
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
//decode base64
$data = base64_decode($data);
//naming image file
$image_name= time().rand(000,999).$k.'.png';
// image path (path) to use upload file to
$path = 'img/location/'. $image_name;
//image path (path2) to save to DB so that summernote can display image in edit mode (When editing summernote content) NB: the difference btwn path and path2 is the forward slash "/" in path2
$path2 = '/img/location/'. $image_name;
file_put_contents($path, $data);
modify image source data in summernote content before upload to DB
$img->removeattribute('src');
$img->setattribute('src', $path2);
}
else {
// not base64 img
}
}
// final variable to store in DB
$detail = $dom->savehtml();
}
- 2 回答
- 0 关注
- 102 浏览
添加回答
举报