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

2022-01-21 00:00:00 string base64 php

我目前正在执行以下操作以在 PHP 中解码 base64 图像:

I am currently doing the following to decode base64 images in 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);

As you can see above we are accepting the four most standard image types (jpeg, png, gif, bmp);

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

However, some of these images are very large and scanning through each one 4-5 times with str_replace seems a dreadful waste and terribly inefficient.

有没有一种方法可以可靠地一次性剥离 base64 图像字符串的 data:image 部分?也许通过检测字符串中的第一个逗号?

Is there a way I could reliably strip the data:image part of a base64 image string in a single pass? Perhaps by detecting the first comma in the string?

如果这是一个简单的问题,我很抱歉,PHP 不是我的强项.提前致谢.

My apologies if this is a simple problem, PHP is not my forte. Thanks in advance.

推荐答案

可以使用正则表达式:

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

如果您要替换的文本是图像中的第一个文本,则在正则表达式的开头添加 ^ 会使其更快,因为它不会分析整个图像,只是前几个字符:

if the text you are replacing is the first text in the image, adding ^ at the beginning of the regexp will make it much faster, because it won't analyze the entire image, just the first few characters:

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

相关文章