【问题标题】:Find and replace multiple base64 images with filenames使用文件名查找和替换多个 base64 图像
【发布时间】:2019-07-06 19:35:32
【问题描述】:

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

请求中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 代码吗?

【问题讨论】:

  • 你用什么编辑器来添加图片?许多编辑器都内置了将图像存储在 amazon s3、数字海洋空间或您自己的服务器上的方法。
  • 我正在制作自己的编辑器,我希望保持这种状态。
  • 明白了。因此,您需要决定是要即时存储图像,还是在保存所有内容时存储它们。例如,使用 amazon s3 和他们的 sdk,您将能够上传图像,然后在回调中获取完整的 URL。然后您可以使用 javascript 通过 id 获取元素并替换为新字符串。
  • 我想在最后存储所有内容,因为在用户最终存储帖子之前可能会有很多编辑。我想将图像保留为 base64 格式,直到用户决定存储它。当时想把base64图片转成文件,存储起来,用保存的图片路径替换src。
  • 为了简单起见,我还尝试对文本中使用的每个图像作为 base64 使用带有 fakepath 的隐藏文件输入,并在请求中传递这些文件,我可以成功地将这些文件保存在服务器端,但问题是是如何将 base64 图像的 src 替换为那些已保存图像的路径。我对两者都使用相似的ID,例如。对于 ID 为“image01”的相应 base64 图像,文件输入 ID 为“img01”。如果有帮助的话。

标签: php laravel image base64


【解决方案1】:

我最终用下面的代码解决了我的问题。我在这里发布它以防其他人需要它。

$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 以显示所有图像文件。我现在可以将返回的字符串存储到数据库中,并嵌入图像路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-13
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 2013-01-29
    相关资源
    最近更新 更多