nic
nic

Reputation: 939

PHP- Failed to save Base64 string to an image file

I have to save base64 file on my local drive, but image corrupted when I have use file_put_contents.

I am able to see the image in my browser using following tag, but when I am using file_put_contents so it's not working.

$data = '<img src="data:image/png;base64,'.$image.'"/>';

code:

$data = '<img src="data:image/png;base64,'.$image.'"/>';
 //$data = str_replace(' ','+',$data);
  $decoded=base64_decode($image);

file_put_contents('/opt/lampp/htdocs/image.png',$decoded);

here is my encoded image content: http://pastebin.com/PtzmceJe

Upvotes: 0

Views: 5910

Answers (3)

oshell
oshell

Reputation: 9123

You have to remove the image tag and only use the src of the tag. String should look like:

data:image/gif;base64,2CiVBORw0KGgoAAAANSUhE

Saving the base64 encoded image

    <?php
    //explode at ',' - the last part should be the encoded image now
    $exp = explode(',', $data);
    //we just get the last element with array_pop
    $base64 = array_pop($exp);
    //decode the image and finally save it
    $data = base64_decode($base64);
    //take care of your file extension
    $file = 'image.gif';
    //make sure you are the owner and have the rights to write content
    file_put_contents($file, $data);

Or directly use the $image variable you have.

    <?php
    //decode the image and finally save it
    $data = base64_decode($image);
    $file = 'data.png';
    //make sure you are the owner and have the rights to write content
    file_put_contents($file, $data);

Upvotes: 1

Michael Coxon
Michael Coxon

Reputation: 5520

Going on the base64 string you have pasted here: http://pastebin.com/PtzmceJe the image is a GIF. The filename is sometimes important depending on the image viewer or OS..

Change your code to this...

$decoded = base64_decode($image);
file_put_contents('/opt/lampp/htdocs/image.gif',$decoded);

.. and it should work for you.

You can see the converted output here https://i.sstatic.net/T43VU.jpg as a GIF.

Upvotes: 2

Manwal
Manwal

Reputation: 23836

Seems like you are wiring wrong content:

$data = '<img src="data:image/png;base64,'.$image.'"/>';
//$decoded=base64_decode($data); wrong $data
$decoded=base64_decode($image); //corrent


file_put_contents('/opt/lampp/htdocs/image.png',$decoded);

Or it may be write permission issue or path issue, try:

file_put_contents('image.png',$decoded);// if dir having write permission it should work then try with complete path

Upvotes: 0

Related Questions