Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a base64 decoded image in the filesystem using php?

I am getting a base64 encoded JPEG string via a POST request to my web service. I want to decode it and save it in the filesystem. How can I achieve this using PHP 5.3. I am able to successfully decode the data using the base64_decode function.

How can I save this decoded string as a JPEG image in the server?

Thanks in advance.

like image 261
Amit Avatar asked Nov 24 '11 06:11

Amit


People also ask

How do I save a Base64 file?

How to convert Base64 to file. Paste your string in the “Base64” field. Press the “Decode Base64 to File” button. Click on the filename link to download the file.

How decode Base64 in PHP?

The base64_decode() is an inbuilt function in PHP which is used to Decodes data which is encoded in MIME base64. Parameters: This function accepts two parameter as mentioned above and described below: $data: It is mandatory parameter which contains the encoded string. $strict: It is an optional parameter.

How do I save a Base64 string as a picture in laravel?

'png'; \File::put(storage_path(). '/' . $imageName, base64_decode($image)); This the Code for covert any Base64 String to Image and store theme in a local path with file name.


2 Answers

If you are sure the image will always be jpg then you can simply use: file_put_contents();

<?php 
$decoded=base64_decode($encodedString);

file_put_contents('newImage.JPG',$decoded);
//leave it to you to randomize the filename.
?>
like image 133
Lawrence Cherone Avatar answered Oct 04 '22 23:10

Lawrence Cherone


Replacing the blank spaces with + signs is required if the data is derived from canvas.toDataURL() function.

 $encodedString = str_replace(' ','+',$encodedString);

See this question

It helped a lot in my case.

like image 24
V.Vachev Avatar answered Oct 04 '22 23:10

V.Vachev