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

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); 

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

However, some of these images are very large and scanning every 4-5 times with str_replace seems like a terrible waste and terribly inefficient.

Is there a way I could reliably split the data: part of the image of a base64 image line in a single pass? Perhaps finding the first comma in the line?

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

+7
source share
3 answers

You can use regex:

 $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 regular expression will make it much faster because it will not parse the entire image, but only the first few characters:

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

The file_get_contents function remove the header and use the base64_decode function, so you get a clear image of the content.

Try this code:

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

You would need to test it, but I think this solution should be a little faster than Mihai Jorg

 $offset = str_pos($s['image'], ','); $data = base64_decode(substr($s['image'], $offset)); 
0
source

All Articles