Skip to content

Instantly share code, notes, and snippets.

@fazlurr
Forked from xjamundx/canvas-upload.php
Created March 27, 2014 07:20
Show Gist options
  • Save fazlurr/9802071 to your computer and use it in GitHub Desktop.
Save fazlurr/9802071 to your computer and use it in GitHub Desktop.
Function to save base64 image to png with PHP
<?php
// requires php5
define('UPLOAD_DIR', 'images/');
$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.';
?>
@jj449
Copy link

jj449 commented Feb 16, 2020

it works ! thank you

Copy link

ghost commented Mar 16, 2020

Dude, you just saved my life (I'm on the edge of a project deadline haha). Thanks bro!

@elvis7t
Copy link

elvis7t commented Mar 19, 2020

define ('UPLOAD_DIR', 'imagens /');
$ img = $ _POST ['img']; // base64 string
$ data = file_get_contents ($ img);
$ arquivo = UPLOAD_DIR. uniqid (). '.png';
$ success = file_put_contents ($ arquivo, $ dados);
print $ sucesso? $ file: 'Não foi possível salvar o arquivo.';

Esse funcionou muito obrigado

@salahbedeiwi
Copy link

$base64 = $_POST['yourImgSrc'];
$image_parts = explode(";base64,", $base64);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1]; //image extension
$image_base64 = base64_decode($image_parts[1]);
$file = ''New Name of your image'.'.$image_type;
$uploadFile = file_put_contents("where to save your file directory/$file", $image_base64); //upload your file

@Edwuards
Copy link

Edwuards commented Oct 22, 2020

$base64 = "data:image/png;base64,gAAAQ8AAAC6CAMAAACHgTh+AA=";

if(preg_match("^data:image\/(?<extension>(?:png|gif|jpg|jpeg));base64,(?<image>.+)$", $base64, $matchings))
{
   $imageData = base64_decode($matchings['image']);
   $extension = $matchings['extension'];
   $filename = sprintf("image.%s", $extension);

   if(file_put_contents($filename, $imageData))
   {
      // image saved
   }
}

You need to add delimiters to the preg_match()

preg_match("/^data:image\/(?<extension>(?:png|gif|jpg|jpeg));base64,(?<image>.+)$/", $base64, $matchings))

@IngLuisCastro
Copy link

Genial, me funcionó

`

$data = $_POST["image"];	

$rand = uniqid();

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

$file = "../firmas/" .  $rand . '.png';

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


$response = array(
	'movefile' => $movefile, 
	'rand' => $rand,
	'file' => $file
);

echo json_encode($response);

`

@shamsulaman786
Copy link

Thanks @fazlurr , it worked perfectly for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment