Amit
Amit

Reputation: 3754

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.

Upvotes: 9

Views: 25046

Answers (2)

V.Vachev
V.Vachev

Reputation: 351

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.

Upvotes: 8

Lawrence Cherone
Lawrence Cherone

Reputation: 46650

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.
?>

Upvotes: 13

Related Questions