10

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 are accepting the four most standard image types (jpeg, png, gif, bmp);

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.

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?

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

gordyr
  • 6,078
  • 14
  • 65
  • 123

5 Answers5

33

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']);
Carlos Campderrós
  • 22,354
  • 11
  • 51
  • 57
  • Perfect! Although all the answers are good and work perfectly. It appears that your method is the fastest, therefore I will award you with the answer as soon as I am able. Many thanks. :) – gordyr Mar 08 '13 at 10:02
25

Function file_get_contents remove header and use base64_decode function, so you get clear content image.

Try this code:

$img = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA0gA...';
$imageContent = file_get_contents($img);
Zameer Khan
  • 1,154
  • 1
  • 18
  • 20
sebob
  • 515
  • 6
  • 14
0

You would have to test it but I think this solution should be slightly faster than Mihai Iorga's

$offset = str_pos($s['image'], ',');
$data = base64_decode(substr($s['image'], $offset));
TFennis
  • 1,393
  • 1
  • 14
  • 23
0

I generete a image with javascript/kendo and send this by ajax to the server.

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

it does not work in this case. in my case this code works better:

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

You can Regular expression for remove image or pdf data formate.

data.replace(/^data:application\/[a-z]+;base64,/, "")
Ankit Kumar Rajpoot
  • 5,188
  • 2
  • 38
  • 32