我如何剥离数据:图像部分从任何图像类型的base64字符串在PHP


How can I strip the data:image part from a base64 string of any image type in PHP

我目前正在做以下解码base64图像在PHP:

   $img = str_replace('data:image/jpeg;base64,', '', $s['image']);
   $img = str_replace('data:image/png;base64,', '', $s['image']);
   $img = str_replace('data:image/gif;base64,', '', $s['image']);
   $img = str_replace('data:image/bmp;base64,', '', $s['image']);
   $img = str_replace(' ', '+', $img);
   $data = base64_decode($img);

正如你在上面看到的,我们接受四种最标准的图像类型(jpeg, png, gif, bmp);

然而,其中一些图像非常大,使用str_replace对每个图像扫描4-5次似乎是一种可怕的浪费,效率极低。

有一种方法,我可以可靠地剥离数据:图像部分的base64图像字符串在一个单一的传递?也许是通过检测字符串中的第一个逗号?

如果这是一个简单的问题,我很抱歉,PHP不是我的强项。

您可以使用正则表达式:

$img = preg_replace('#data:image/[^;]+;base64,#', '', $s['image']);

如果你要替换的文本是图像中的第一个文本,在regexp的开头添加^将使它更快,因为它不会分析整个图像,只分析前几个字符:

$img = preg_replace('#^data:image/[^;]+;base64,#', '', $s['image']);

Function file_get_contents remove header and use base64_decode Function所以你得到了清晰的内容图像。

试试这个代码:

$img = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA0gA...';
$imageContent = file_get_contents($img);

你必须测试它,但我认为这个解决方案应该比Mihai Iorga的

快一些。
$offset = str_pos($s['image'], ',');
$data = base64_decode(substr($s['image'], $offset));

我用javascript/kendo生成一个图像,并通过ajax将其发送到服务器。

preg_replace('#^data:image/[^;]+;base64,#', '', $s['image']); 

在这种情况下不起作用。在我的例子中,下面的代码效果更好:

$contentType  = mime_content_type($s['image']);
$img = preg_replace('#^data:image/(.*?);base64,#i', '$2', $s['image']);

您可以使用正则表达式删除图像或pdf数据格式。

data.replace(/^data:application'/[a-z]+;base64,/, "")