如何从PHP中任何图像类型的base64字符串中剥离data:image部分 [英] How can I strip the data:image part from a base64 string of any image type in PHP

查看:896
本文介绍了如何从PHP中任何图像类型的base64字符串中剥离data:image部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在执行以下操作以解码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.

推荐答案

您可以使用正则表达式:

You can use a regular expression:

$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']);

这篇关于如何从PHP中任何图像类型的base64字符串中剥离data:image部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆