Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

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

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.

like image 963
gordyr Avatar asked Mar 08 '13 09:03

gordyr


People also ask

How can I strip the data image part from a Base64 string of any image type in C#?

var strImage = strToReplace. replace(/^data:image\/[a-z]+;base64,/, "");

How do I view Base64 encoded images?

Images encoded with Base64 can be embedded in HTML by using the <img> tag. This can help to increase the page load time for smaller images by saving the browser from making additional HTTP requests.

Is it good to store Base64 image in database?

Generally no. Base64 will occupy more space than necessary to store those images. Depending on the size of your images and how frequently they're accessed, it is generally not an optimal stress to put on the database. You should store them on the file system or in something like Azure blob storage.


2 Answers

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']);
like image 141
Carlos Campderrós Avatar answered Sep 23 '22 08:09

Carlos Campderrós


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);
like image 23
sebob Avatar answered Sep 19 '22 08:09

sebob