I'm nidhin
I'm nidhin

Reputation: 2662

base64 image to png not working php

Im trying to convert base64 image to png.This is my code

$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';

The file is created successfully. But it could not be open.Its not in a readable format.

Upvotes: 0

Views: 1978

Answers (1)

Ivan
Ivan

Reputation: 1241

Sorry for reviving your question, but take a look, it worked like charm:

<?php

$img = $_POST['Base64Variable'];
define('UPLOAD_DIR', 'YourFolder/');


$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);

$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';

$success = file_put_contents($file, $data);

print $success ? $file : 'Could not save the file!';

?>

Upvotes: 1

Related Questions