查找并用文件名替换多个base64图像

时间:2019-07-06 19:35:32

标签: php laravel image base64

在开始之前,我将Laravel 5.7用于我的项目,但是任何php解决方案都可以使用。 我正在网站上创建一个简单的编辑器,用户可以在其中进行简单的编辑以及添加图像。我为此使用contenteditable div。当我将图像添加到div时,它将被添加为base64图像。提交表单后,我想将这些图像另存为服务器端的文件,然后将这些图像的src替换为在字符串中新保存图像的路径,然后再将其保存在数据库中。我没有找到提交contenteditable div的方法,因此在提交之前,我将所有文本从div传输到了隐藏的textarea。如果还有其他可靠的方法可以纠正我。 这是我要找的东西:

请求中的文本区域的原始示例内容:-

"This is a test post with some images like this one 
<img src="data:image/jpeg;base64,/9j.....long base 64 string...." id="img02">
and it can contain more than one images like here is the second image
<img src="data:image/png;base64,/8Aue.....long base 64 string...." id="img01">
and more images like this"

预期输出:-

"This is a test post with some images like this one  
<img src="my_public_path/Unique_file_name.jpg" id="img02"> 
and it can contain more than one images like here is the second image 
<img src="my_public_path/Unique_file_name.png" id="img01"> 
and more images like this"

有人可以指出正确的方向或向我提供php代码来实现这一目标吗?

1 个答案:

答案 0 :(得分:0)

我最终通过以下代码解决了我的问题。我将其发布在这里,以防万一其他人需要它。

$stt = $request->storytextTemp; // string containing base64 encoded image files.
preg_match('#data:image/(gif|png|jpeg);base64,([\w=+/]++)#', $stt, $x);
while(isset($x[0]))
{
    $imgdata = base64_decode($x[0]);
    $info = explode(";", explode("/", $x[0])[1])[0];
    $textareaImages = $request->imagesTextarea;

    $imm = Image::make(file_get_contents($x[0]));
    $imp = public_path().'/images/tempStoryImages/';
    $imn = date('y_m_d') . "_" . uniqid().".".$info;
    $imm->save($imp.$imn);

    $stt = str_replace($x[0], 'http://127.0.0.1:8000/images/tempStoryImages/'.$imn, $stt);
    preg_match('#data:image/(gif|png|jpeg);base64,([\w=+/]++)#', $stt, $x);
}
return $stt;

上面的程序将我所有的图像保存在tempStoryImages文件夹中,并返回html以显示所有图像文件。现在,我可以将返回的字符串存储到数据库中,并在其中嵌入图像路径。