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.';
?>
@mickytroxxy
Copy link

its because your image is too big, try smaller images

@gajendra-chauhan123
Copy link

my code is not not workin, i am not seeing actual image,Please give a best solution

@shahzadm287
Copy link

define('UPLOAD_DIR', 'uploads/');
foreach ($_REQUEST['image'] as $value) {
$img = $value;
$img = str_replace('data:image/jpeg;base64,', '', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
$data1[] = $file;
}
echo json_encode($data1);

this code is working as per my requirements.
thanks

@mohamedbrahimi
Copy link

thanks this code is woking perfectly, but the image file was damaged and corrupte, any one give the best solution !!

@Airone2000
Copy link

$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
   }
}

@RomeoDenis
Copy link

RomeoDenis commented Oct 27, 2018

define('UPLOAD_DIR', 'images/');
$img = $_POST['img']; //base64 string
$data = file_get_contents($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';

@kaled-hoshme
Copy link

`<?php

function create_image($name,$directory){
define('UPLOAD_DIR', $directory);
$img = base64_encode(file_get_contents( $_FILES[$name]["tmp_name"] ));
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$basename=uniqid();
$file = UPLOAD_DIR . $basename . '.png';
$success=file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
return $basename.'.png';
}

`

@srheede
Copy link

srheede commented Jan 21, 2019

Just what I was looking for! Thanks so much!!

@augustocparaujo
Copy link

Showw, thank you, you're excellent.

@VinayakYadav
Copy link

Thank so much! kaled-hoshme

@imdad6053
Copy link

	if(isset($_POST['submit'])){
		define('UPLOAD_DIR', 'img/');

		$img = $_POST['image'];

		$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.';
	}		


	<form method="post"  name="change" enctype="multipart-form/data">

		<!-- <img src="" id="img" name="image" >  -->
		<input type="text" name="image" id="img" hidden="hidden" value="base64Code">

		<input type="submit" name="submit">

	</form>

@erdenayozkanl
Copy link

what is UPLOAD_DIR is it constant we should use or is it path?

define('UPLOAD_DIR', 'img/');

@iambasilk
Copy link

It worked!

@tbiinfotech
Copy link

Thank you. Working fine

@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