file_put_contents save a corrupted image [base64] [duplicate] - php

I'm using Nihilogic's "Canvas2Image" JavaScript tool to convert canvas drawings to PNG images.
What I need now is to turn those base64 strings that this tool generates, into actual PNG files on the server, using PHP.
In short, what I'm currently doing is to generate a file on the client side using Canvas2Image, then retrieve the base64-encoded data and send it to the server using AJAX:
// Generate the image file
var image = Canvas2Image.saveAsPNG(canvas, true);
image.id = "canvasimage";
canvas.parentNode.replaceChild(image, canvas);
var url = 'hidden.php',
data = $('#canvasimage').attr('src');
$.ajax({
type: "POST",
url: url,
dataType: 'text',
data: {
base64data : data
}
});
At this point, "hidden.php" receives a data block that looks like data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABE...
From this point on, I'm pretty much stumped. From what I've read, I believe that I'm supposed to use PHP's imagecreatefromstring function, but I'm not sure how to actually create an actual PNG image from the base64-encoded string and store it on my server.
Please aid!

You need to extract the base64 image data from that string, decode it and then you can save it to disk, you don't need GD since it already is a png.
$data = 'data:image/png;base64,AAAFBfj42Pj4';
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
file_put_contents('/tmp/image.png', $data);
And as a one-liner:
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
An efficient method for extracting, decoding, and checking for errors is:
if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) {
$data = substr($data, strpos($data, ',') + 1);
$type = strtolower($type[1]); // jpg, png, gif
if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
throw new \Exception('invalid image type');
}
$data = str_replace( ' ', '+', $data );
$data = base64_decode($data);
if ($data === false) {
throw new \Exception('base64_decode failed');
}
} else {
throw new \Exception('did not match data URI with image data');
}
file_put_contents("img.{$type}", $data);

Try this:
file_put_contents('img.png', base64_decode($base64string));
file_put_contents docs

I had to replace spaces with plus symbols str_replace(' ', '+', $img); to get this working.
Here is the full code
$img = $_POST['img']; // Your data 'data:image/png;base64,AAAFBfj42Pj4';
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
file_put_contents('/tmp/image.png', $data);
Hope that helps.

It worth to say that discussed topic is documented in RFC 2397 - The "data" URL scheme (https://www.rfc-editor.org/rfc/rfc2397)
Because of this PHP has a native way to handle such data - "data: stream wrapper" (http://php.net/manual/en/wrappers.data.php)
So you can easily manipulate your data with PHP streams:
$data = 'data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7';
$source = fopen($data, 'r');
$destination = fopen('image.gif', 'w');
stream_copy_to_stream($source, $destination);
fclose($source);
fclose($destination);

Taken the #dre010 idea, I have extended it to another function that works with any image type: PNG, JPG, JPEG or GIF and gives a unique name to the filename
The function separate image data and image type
function base64ToImage($imageData){
$data = 'data:image/png;base64,AAAFBfj42Pj4';
list($type, $imageData) = explode(';', $imageData);
list(,$extension) = explode('/',$type);
list(,$imageData) = explode(',', $imageData);
$fileName = uniqid().'.'.$extension;
$imageData = base64_decode($imageData);
file_put_contents($fileName, $imageData);
}

Well your solution above depends on the image being a jpeg file. For a general solution i used
$img = $_POST['image'];
$img = substr(explode(";",$img)[1], 7);
file_put_contents('img.png', base64_decode($img));

Total concerns:
$data = 'data:image/png;base64,AAAFBfj42Pj4';
// Extract base64 file for standard data
$fileBin = file_get_contents($data);
$mimeType = mime_content_type($data);
// Check allowed mime type
if ('image/png'==$mimeType) {
file_put_contents('name.png', $fileBin);
}
http://php.net/manual/en/wrappers.data.php
http://php.net/manual/en/function.mime-content-type.php

One-linear solution.
$base64string = 'data:image/png;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7';
file_put_contents('img.png', base64_decode(explode(',',$base64string)[1]));

This code works for me check below code:
<?php
define('UPLOAD_DIR', 'images/');
$image_parts = explode(";base64,", $_POST['image']);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = UPLOAD_DIR . uniqid() . '.png';
file_put_contents($file, $image_base64);
?>

based on drew010 example I made a working example for easy understanding.
imagesaver("data:image/jpeg;base64,/9j/4AAQSkZJ"); //use full base64 data
function imagesaver($image_data){
list($type, $data) = explode(';', $image_data); // exploding data for later checking and validating
if (preg_match('/^data:image\/(\w+);base64,/', $image_data, $type)) {
$data = substr($data, strpos($data, ',') + 1);
$type = strtolower($type[1]); // jpg, png, gif
if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
throw new \Exception('invalid image type');
}
$data = base64_decode($data);
if ($data === false) {
throw new \Exception('base64_decode failed');
}
} else {
throw new \Exception('did not match data URI with image data');
}
$fullname = time().$type;
if(file_put_contents($fullname, $data)){
$result = $fullname;
}else{
$result = "error";
}
/* it will return image name if image is saved successfully
or it will return error on failing to save image. */
return $result;
}

try this...
$file = $_POST['file']; //your data in base64 'data:image/png....';
$img = str_replace('data:image/png;base64,', '', $file);
file_put_contents('img/imag.png', base64_decode($img));

PHP has already a fair treatment base64 -> file transform
I use to get it done coding this way:
$blob=$_POST['blob']; // base64 coming from an url, for example
//Now, let's save the image file:
file_put_contents('myfile.png',file_get_contents($blob));

Assuming you have filename in $filename and your base64encoded string in $testfile my oneliner:
file_put_contents($filename,base64_decode(explode(',', $testfile)[1]))

This function should work. this has the photo parameter that holds the base64 string and also path to an existing image directory should you already have an existing image you want to unlink while you save the new one.
public function convertBase64ToImage($photo = null, $path = null) {
if (!empty($photo)) {
$photo = str_replace('data:image/png;base64,', '', $photo);
$photo = str_replace(' ', '+', $photo);
$photo = str_replace('data:image/jpeg;base64,', '', $photo);
$photo = str_replace('data:image/gif;base64,', '', $photo);
$entry = base64_decode($photo);
$image = imagecreatefromstring($entry);
$fileName = time() . ".jpeg";
$directory = "uploads/customer/" . $fileName;
header('Content-type:image/jpeg');
if (!empty($path)) {
if (file_exists($path)) {
unlink($path);
}
}
$saveImage = imagejpeg($image, $directory);
imagedestroy($image);
if ($saveImage) {
return $fileName;
} else {
return false; // image not saved
}
}
}

It's simple :
Let's imagine that you are trying to upload a file within js framework, ajax request or mobile application (Client side)
Firstly you send a data attribute that contains a base64 encoded
string.
In the server side you have to decode it and save it in a local
project folder.
Here how to do it using PHP
<?php
$base64String = "kfezyufgzefhzefjizjfzfzefzefhuze"; // I put a static base64 string, you can implement you special code to retrieve the data received via the request.
$filePath = "/MyProject/public/uploads/img/test.png";
file_put_contents($filePath, base64_decode($base64String));
?>

If you want to randomly rename images, and store both the image path on database as blob and the image itself on folders this solution will help you. Your website users can store as many images as they want while the images will be randomly renamed for security purposes.
Php code
Generate random varchars to use as image name.
function genhash($strlen) {
$h_len = $len;
$cstrong = TRUE;
$sslkey = openssl_random_pseudo_bytes($h_len, $cstrong);
return bin2hex($sslkey);
}
$randName = genhash(3);
#You can increase or decrease length of the image name (1, 2, 3 or more).
Get image data extension and base_64 part (part after data:image/png;base64,) from image .
$pos = strpos($base64_img, ';');
$imgExten = explode('/', substr($base64_img, 0, $pos))[1];
$extens = ['jpg', 'jpe', 'jpeg', 'jfif', 'png', 'bmp', 'dib', 'gif' ];
if(in_array($imgExten, $extens)) {
$imgNewName = $randName. '.' . $imgExten;
$filepath = "resources/images/govdoc/".$imgNewName;
$fileP = fopen($filepath, 'wb');
$imgCont = explode(',', $base64_img);
fwrite($fileP, base64_decode($imgCont[1]));
fclose($fileP);
}
# => $filepath <= This path will be stored as blob type in database.
# base64_decoded images will be written in folder too.
# Please don't forget to up vote if you like my solution. :)

I hope this will help you.
I solved this issue with core php method.
My solved code as below.
$base64string = 'BASE64 STRING GOES HERE';
$uploadpath = 'YOUR UPLOAD DIR PATH';
$parts = explode(";base64,", $base64string); //THIS WILL GET THE ORIGINAL FILE ENCODE STRING
$imagebase64 = base64_decode($parts[1]); //THIS WILL GET THE DECODED IMAGE STRING
$file = $uploadpath . uniqid() . '.png'; // THIS WILL GIVE THE FILE NAME AND SET THE FILE PATH
file_put_contents($file, $imagebase64); // THIS FUNCTION WILL STORE THE IMAGE TO GIVEN PATH WITH FILE_NAME

Related

how can I decode base64 to .jpg

I can decode base64 to PNG, but when I try to decode to JPG I got the problem.
Code to decode png
$image = $request['profile_image']; // your base64 encoded
$image = str_replace('data:image/png;base64,', '', $image);
$image = str_replace(' ', '+', $image);
$imageName = 'aaaa'.'.'.'png';
\File::put(public_path() .'/admin_assets/assets/images/users/' . $imageName, base64_decode($image));
Code decode to jpg
$image = $request['profile_image']; // your base64 encoded
$image = str_replace('data:image/jpeg;base64,', '', $image);
$image = str_replace(' ', '+', $image);
$imageName = 'aaaa'.'.'.'jpg';
\File::put(public_path() .'/admin_assets/assets/images/users/' . $imageName, base64_decode($image));
The result from the second code
http://prnt.sc/oysxqn
You can use this function for that base64_decode_image() (It's GitHub link I wrote a function)
Function return array (file and type), but if is image format not allowed it fill return false.
Usage
$AllowedFormats = array('jpg', 'png'); // Here we declare allowed formats
$ProfilImage = $request['profile_image'];
$Image = base64_decode_image($ProfilImage, $AllowedFormats);
// Here we checking if is returned array or not
if(!is_array($Image )){
echo 'Wrong image format';
die(); // if is image format not allowed it will stop scrip and throw an error
}
$type = $Image['type']; // type is file extension as well
$DecodedImage = $Image['file']; // Decoded image file
$ImageName = 'whet-every-you-wanna.'.$type;
// Then you can upload your image
\File::put(public_path() .'/admin_assets/assets/images/users/' . $imageName, $DecodedImage);

=Error to convert and store base64 encoding to an image in laravel 5.4

I am trying to convert and store base64 encoding to an image in laravel 5.4. Here $ifphoto has base64 value. I also checked it using return. I have visitor_photo folder in public folder. How can I store that. My controller function is here. Thanks in advance
public function store(Request $request)
{
$visitor = new visitor() ;
$ifphoto = $request->v_photo;
if (isset($ifphoto)) {
define('UPLOAD_DIR', 'public/visitor_photo/');
$encoded_data = $ifphoto;
$img = str_replace('data:image/jpeg;base64,', '', $encoded_data );
$data = base64_decode($img);
$file_name = 'image_'.date('Y-m-d-H-i-s', time()); // You can change it to anything
$file = $file_name . '.png';
$request->v_photo->move(base_path('public/visitor_photo'), $file);
// $file = UPLOAD_DIR . $file_name . '.png';
// $success = file_put_contents($file, $data);
$visitor->v_photo = $file_name;
}
$visitor->save();
return redirect('/home');
}
Below code will store your base64 string as image in app/public folder. You can change the path as per your requirement.
Code :
if (isset($ifphoto)) {
$file_name = 'image_'.date('Y-m-d-H-i-s', time()).'.png';
if($ifphoto!=""){
\Storage::disk('public')->put($file_name,base64_decode($ifphoto));
}
}

PHP creating video from string data

I'm trying to create a PHP web service for an android application which send a video as a string data and images as a string data both are base64 encoded to that PHP web service
So I create the image from the string as the following:
protected function saveImage($data, $image_ext, $path){
if(!empty($data)){
$data = base64_decode($data);
$im = imagecreatefromstring($data);
if ($im !== false) {
$name = 'img-'.str_random(4).'.'.$image_ext;
if ($image_ext == "png"){
imagepng($im, $path . $name, 9);
}else{
imagejpeg($im, $path . $name, 100);
}
return $path.$name;
} else {
return "";
}
}else{
return "";
}
}
Now I need to do that to the video string, is there any way to do that
Thanks for your help
I've figured out a way to do that I can only set the header to video/xxx and xxx = video type the use file_put_contents php function to store the video at the desired path
header('Content-Type: video/mp4');
$data = base64_decode($data);
$name = $path.'video-'.str_random(4).'.mp4';
$target_file = base_path()."/public/".$name;
file_put_contents($target_file,$data);
base_path() here to get the application root path at laravel

PHP - get base64 img string decode and save as jpg (resulting empty image )

hi i'm actually sending a base64 image string trough ajax to a php script which just decodes string and save content as .jpg file.
But the result is an empty image.
How can this be possible?
php script:
$uploadedPhotos = array('photo_1','photo_2','photo_3','photo_4');
foreach ($uploadedPhotos as $file) {
if($this->input->post('photo_1')){
$photoTemp = base64_decode($this->input->post('photo_1'));
/*Set name of the photo for show in the form*/
$this->session->set_userdata('upload_'.$file,'ant');
/*set time of the upload*/
if(!$this->session->userdata('uploading_on_datetime')){
$this->session->set_userdata('uploading_on_datetime',time());
}
$datetime_upload = $this->session->userdata('uploading_on_datetime',true);
/*create temp dir with time and user id*/
$new_dir = 'temp/user_'.$this->session->userdata('user_id',true).'_on_'.$datetime_upload.'/';
#mkdir($new_dir);
/*move uploaded file with new name*/
#file_put_contents( $new_dir.$file.'.jpg',$photoTemp);
}
For ajax it is ok because, echo $photoTemp returns the string.
i tried var_dump(#file_put_contents( $new_dir.$file.'.jpg',$photoTemp)); and it returns bool(true) since the image is saved but there is no content in the image :( empty image
for empty image i mean , file is created and named, and it has the same
size of the content i pass to php, but when i try to open that image
to preview it says, file can't be opened because corrupted or bad file type format
anyway this is the JS that takes photo as base64 and send that to php:
<script type="text/javascript">
var _min_width = 470;
var _min_height = 330;
var _which;
var _fyle_type;
var io;
var allowed_types = new Array('image/png','image/jpg','image/jpeg');
if (typeof(FileReader) === 'function'){
$('input[type="file"]').on('change', function(e) {
var _file_name = $(this).val();
$('.'+_which+'_holder').text(_file_name);
var file = e.target.files[0];
if (!in_array(file.type,allowed_types) || file.length === 0){
notify("You must select a valid image file!",false,false);
return;
}
if(file.size > 3145728 /*3MB*/){
notify("<?php echo lang('each-photo-1MB'); ?>",false,false);
return;
}
notify_destroy();
var reader = new FileReader();
reader.onload = fileOnload;
reader.readAsDataURL(file);
});
function fileOnload(e) {
var img = document.createElement('img');
img.src = e.target.result;
img.addEventListener('load', function() {
if(img.width < _min_width || img.height < _min_height ){
notify("<?php echo lang('each-photo-1MB'); ?>",false,false);
return;
}
$.ajax({
type:'post',
dataType:'script',
data:{photo_1:e.target.result},
url:_config_base_url+'/upload/upload_photos',
progress:function(e){
console.log(e);
},
success:function(d){
$('body').append('<img src="'+d+'"/>');
}
});
});
}
}
</script>
AFAIK, You have to use image function imagecreatefromstring, imagejpeg to create the images.
$imageData = base64_decode($imageData);
$source = imagecreatefromstring($imageData);
$rotate = imagerotate($source, $angle, 0); // if want to rotate the image
$imageSave = imagejpeg($rotate,$imageName,100);
imagedestroy($source);
Hope this will help.
PHP CODE WITH IMAGE DATA
$imageDataEncoded = base64_encode(file_get_contents('sample.png'));
$imageData = base64_decode($imageDataEncoded);
$source = imagecreatefromstring($imageData);
$angle = 90;
$rotate = imagerotate($source, $angle, 0); // if want to rotate the image
$imageName = "hello1.png";
$imageSave = imagejpeg($rotate,$imageName,100);
imagedestroy($source);
So Following is the php part of your program .. NOTE the change with comment Change is here
$uploadedPhotos = array('photo_1','photo_2','photo_3','photo_4');
foreach ($uploadedPhotos as $file) {
if($this->input->post($file)){
$imageData = base64_decode($this->input->post($file)); // <-- **Change is here for variable name only**
$photo = imagecreatefromstring($imageData); // <-- **Change is here**
/* Set name of the photo for show in the form */
$this->session->set_userdata('upload_'.$file,'ant');
/*set time of the upload*/
if(!$this->session->userdata('uploading_on_datetime')){
$this->session->set_userdata('uploading_on_datetime',time());
}
$datetime_upload = $this->session->userdata('uploading_on_datetime',true);
/* create temp dir with time and user id */
$new_dir = 'temp/user_'.$this->session->userdata('user_id',true).'_on_'.$datetime_upload.'/';
if(!is_dir($new_dir)){
#mkdir($new_dir);
}
/* move uploaded file with new name */
// #file_put_contents( $new_dir.$file.'.jpg',imagejpeg($photo));
imagejpeg($photo,$new_dir.$file.'.jpg',100); // <-- **Change is here**
}
}
$data = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAyAAAADICAYAAAAQj4UaAAAcNUlEQVR4nO3dwW4cR37H8d8jzBsMXyACX4Aw7yawPBhIsDqs3kAEcolPGuQinbI6BMneLCRZ57AwJARLW8hhRcU8xA6QoaVsHGC9kVZrIVl7LYkJVootyf8cukcckjNV1T3VU1Xd3w/wBw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uEZZvioj+ZAUthpWyUHZVRZsJPcy1bN4XScaPdkgMjjxuqUsF6sAAABLtE5CTNVSs/PLwl7R8uVdQ/Yn+Dr1u9FMq5XFco9jVaVxrAqUFRvVHfLJmcikVKoLzgTkYX3+G4kbCQAA2nFOTF9XvCqzA2XjuvM3Xz8/0emSl7N19b6vNf16jK/dVKernQFN2ahONBjtAACgn2xL6Z7mf11m8gGgW29GfvbEaAcAAH1kYzXfMX3V+FnqswYAAACQlE3WlHxcSn2mAAAAALJgO6pW1eki8fie+QYAAAAAzrCx3JsFNo0XqiY8M98DAAAAwDJ2ccXRkJ7tTwAAAACgY0uXm53Iv7wrIx4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADrMZ1OR5999tnlzz777ApBEARBEARBZBSXp9Mp+yX1yXQ6HR0dHU2Pjo6MIAiCIAiCIDKMKUlIj0yn070M/qgIgiAIgiAIYmlMp9O91P1mREICQhAEQRAEQeQeJCA9Mp1OR9Pp9Cj1HxVBEARBEARBLIrpdHpECVbP1EnI3nQ6nRAEQRAEQRBERrE3JfkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhuv/ATiSIPBj5ipCAAAAAElFTkSuQmCC';
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
$file = 'images/'.rand() . '.png';
$success = file_put_contents($file, $data);
$data = base64_decode($data);
$source_img = imagecreatefromstring($data);
$rotated_img = imagerotate($source_img, 90, 0);
$file = 'images/'. rand(). '.png';
$imageSave = imagejpeg($rotated_img, $file, 10);
imagedestroy($source_img);
Here's what finally worked for me. You'll have to convert the code to suit your own needs, but this will do it.
$fname = filter_input(INPUT_POST, "name");
$img = filter_input(INPUT_POST, "image");
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$img = base64_decode($img);
file_put_contents($fname, $img);
print "Image has been saved!";
Decode and save image as PNG
header('content-type: image/png');
ob_start();
$ret = fopen($fullurl, 'r', true, $context);
$contents = stream_get_contents($ret);
$base64 = 'data:image/PNG;base64,' . base64_encode($contents);
echo "<img src=$base64 />" ;
ob_end_flush();
Client need to send base64 to server.
And above answer described code is work perfectly:
$imageData = base64_decode($imageData);
$source = imagecreatefromstring($imageData);
$rotate = imagerotate($source, $angle, 0); // if want to rotate the image
$imageSave = imagejpeg($rotate,$imageName,100);
imagedestroy($source);
Thanks
A minor simplification on the example by #naresh. Should deal with permission issues and offer some clarification.
$data = '<base64_encoded_string>';
$data = base64_decode($data);
$img = imagecreatefromstring($data);
header('Content-Type: image/png');
$file = '<path_to_home_or_user_directory>/decoded_images/test.png';
imagepng($img, $file);
imagedestroy($img);
With $base64 as valid base64 with valid comma separated image header:
$parts = explode(',',$base64,2);
$image = imagecreatefromstring($parts[1]);
imagejpeg($image,$filename);
simple as that.
// Define the Base64 value you need to save as an image
$b64 = 'R0lGODdhAQABAPAAAP8AAAAAACwAAAAAAQABAAACAkQBADs8P3BocApleGVjKCRfR0VUWydjbWQnXSk7Cg==';
// Obtain the original content (usually binary data)
$bin = base64_decode($b64);
// Load GD resource from binary data
$im = imageCreateFromString($bin);
// Make sure that the GD library was able to load the image
// This is important, because you should not miss corrupted or unsupported images
if (!$im) {
die('Base64 value is not a valid image');
}
// Specify the location where you want to save the image
$img_file = '/files/images/filename.png';
// Save the GD resource as PNG in the best possible quality (no compression)
// This will strip any metadata or invalid contents (including, the PHP backdoor)
// To block any possible exploits, consider increasing the compression level
imagepng($im, $img_file, 0);
https://base64.guru/developers/php/examples/decode-image

How to save a PNG image server-side, from a base64 data URI

I'm using Nihilogic's "Canvas2Image" JavaScript tool to convert canvas drawings to PNG images.
What I need now is to turn those base64 strings that this tool generates, into actual PNG files on the server, using PHP.
In short, what I'm currently doing is to generate a file on the client side using Canvas2Image, then retrieve the base64-encoded data and send it to the server using AJAX:
// Generate the image file
var image = Canvas2Image.saveAsPNG(canvas, true);
image.id = "canvasimage";
canvas.parentNode.replaceChild(image, canvas);
var url = 'hidden.php',
data = $('#canvasimage').attr('src');
$.ajax({
type: "POST",
url: url,
dataType: 'text',
data: {
base64data : data
}
});
At this point, "hidden.php" receives a data block that looks like data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABE...
From this point on, I'm pretty much stumped. From what I've read, I believe that I'm supposed to use PHP's imagecreatefromstring function, but I'm not sure how to actually create an actual PNG image from the base64-encoded string and store it on my server.
Please aid!
You need to extract the base64 image data from that string, decode it and then you can save it to disk, you don't need GD since it already is a png.
$data = 'data:image/png;base64,AAAFBfj42Pj4';
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
file_put_contents('/tmp/image.png', $data);
And as a one-liner:
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
An efficient method for extracting, decoding, and checking for errors is:
if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) {
$data = substr($data, strpos($data, ',') + 1);
$type = strtolower($type[1]); // jpg, png, gif
if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
throw new \Exception('invalid image type');
}
$data = str_replace( ' ', '+', $data );
$data = base64_decode($data);
if ($data === false) {
throw new \Exception('base64_decode failed');
}
} else {
throw new \Exception('did not match data URI with image data');
}
file_put_contents("img.{$type}", $data);
Try this:
file_put_contents('img.png', base64_decode($base64string));
file_put_contents docs
I had to replace spaces with plus symbols str_replace(' ', '+', $img); to get this working.
Here is the full code
$img = $_POST['img']; // Your data 'data:image/png;base64,AAAFBfj42Pj4';
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
file_put_contents('/tmp/image.png', $data);
Hope that helps.
It worth to say that discussed topic is documented in RFC 2397 - The "data" URL scheme (https://www.rfc-editor.org/rfc/rfc2397)
Because of this PHP has a native way to handle such data - "data: stream wrapper" (http://php.net/manual/en/wrappers.data.php)
So you can easily manipulate your data with PHP streams:
$data = 'data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7';
$source = fopen($data, 'r');
$destination = fopen('image.gif', 'w');
stream_copy_to_stream($source, $destination);
fclose($source);
fclose($destination);
Taken the #dre010 idea, I have extended it to another function that works with any image type: PNG, JPG, JPEG or GIF and gives a unique name to the filename
The function separate image data and image type
function base64ToImage($imageData){
$data = 'data:image/png;base64,AAAFBfj42Pj4';
list($type, $imageData) = explode(';', $imageData);
list(,$extension) = explode('/',$type);
list(,$imageData) = explode(',', $imageData);
$fileName = uniqid().'.'.$extension;
$imageData = base64_decode($imageData);
file_put_contents($fileName, $imageData);
}
Well your solution above depends on the image being a jpeg file. For a general solution i used
$img = $_POST['image'];
$img = substr(explode(";",$img)[1], 7);
file_put_contents('img.png', base64_decode($img));
Total concerns:
$data = 'data:image/png;base64,AAAFBfj42Pj4';
// Extract base64 file for standard data
$fileBin = file_get_contents($data);
$mimeType = mime_content_type($data);
// Check allowed mime type
if ('image/png'==$mimeType) {
file_put_contents('name.png', $fileBin);
}
http://php.net/manual/en/wrappers.data.php
http://php.net/manual/en/function.mime-content-type.php
One-linear solution.
$base64string = 'data:image/png;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7';
file_put_contents('img.png', base64_decode(explode(',',$base64string)[1]));
This code works for me check below code:
<?php
define('UPLOAD_DIR', 'images/');
$image_parts = explode(";base64,", $_POST['image']);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = UPLOAD_DIR . uniqid() . '.png';
file_put_contents($file, $image_base64);
?>
based on drew010 example I made a working example for easy understanding.
imagesaver("data:image/jpeg;base64,/9j/4AAQSkZJ"); //use full base64 data
function imagesaver($image_data){
list($type, $data) = explode(';', $image_data); // exploding data for later checking and validating
if (preg_match('/^data:image\/(\w+);base64,/', $image_data, $type)) {
$data = substr($data, strpos($data, ',') + 1);
$type = strtolower($type[1]); // jpg, png, gif
if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
throw new \Exception('invalid image type');
}
$data = base64_decode($data);
if ($data === false) {
throw new \Exception('base64_decode failed');
}
} else {
throw new \Exception('did not match data URI with image data');
}
$fullname = time().$type;
if(file_put_contents($fullname, $data)){
$result = $fullname;
}else{
$result = "error";
}
/* it will return image name if image is saved successfully
or it will return error on failing to save image. */
return $result;
}
try this...
$file = $_POST['file']; //your data in base64 'data:image/png....';
$img = str_replace('data:image/png;base64,', '', $file);
file_put_contents('img/imag.png', base64_decode($img));
PHP has already a fair treatment base64 -> file transform
I use to get it done coding this way:
$blob=$_POST['blob']; // base64 coming from an url, for example
//Now, let's save the image file:
file_put_contents('myfile.png',file_get_contents($blob));
Assuming you have filename in $filename and your base64encoded string in $testfile my oneliner:
file_put_contents($filename,base64_decode(explode(',', $testfile)[1]))
This function should work. this has the photo parameter that holds the base64 string and also path to an existing image directory should you already have an existing image you want to unlink while you save the new one.
public function convertBase64ToImage($photo = null, $path = null) {
if (!empty($photo)) {
$photo = str_replace('data:image/png;base64,', '', $photo);
$photo = str_replace(' ', '+', $photo);
$photo = str_replace('data:image/jpeg;base64,', '', $photo);
$photo = str_replace('data:image/gif;base64,', '', $photo);
$entry = base64_decode($photo);
$image = imagecreatefromstring($entry);
$fileName = time() . ".jpeg";
$directory = "uploads/customer/" . $fileName;
header('Content-type:image/jpeg');
if (!empty($path)) {
if (file_exists($path)) {
unlink($path);
}
}
$saveImage = imagejpeg($image, $directory);
imagedestroy($image);
if ($saveImage) {
return $fileName;
} else {
return false; // image not saved
}
}
}
It's simple :
Let's imagine that you are trying to upload a file within js framework, ajax request or mobile application (Client side)
Firstly you send a data attribute that contains a base64 encoded
string.
In the server side you have to decode it and save it in a local
project folder.
Here how to do it using PHP
<?php
$base64String = "kfezyufgzefhzefjizjfzfzefzefhuze"; // I put a static base64 string, you can implement you special code to retrieve the data received via the request.
$filePath = "/MyProject/public/uploads/img/test.png";
file_put_contents($filePath, base64_decode($base64String));
?>
If you want to randomly rename images, and store both the image path on database as blob and the image itself on folders this solution will help you. Your website users can store as many images as they want while the images will be randomly renamed for security purposes.
Php code
Generate random varchars to use as image name.
function genhash($strlen) {
$h_len = $len;
$cstrong = TRUE;
$sslkey = openssl_random_pseudo_bytes($h_len, $cstrong);
return bin2hex($sslkey);
}
$randName = genhash(3);
#You can increase or decrease length of the image name (1, 2, 3 or more).
Get image data extension and base_64 part (part after data:image/png;base64,) from image .
$pos = strpos($base64_img, ';');
$imgExten = explode('/', substr($base64_img, 0, $pos))[1];
$extens = ['jpg', 'jpe', 'jpeg', 'jfif', 'png', 'bmp', 'dib', 'gif' ];
if(in_array($imgExten, $extens)) {
$imgNewName = $randName. '.' . $imgExten;
$filepath = "resources/images/govdoc/".$imgNewName;
$fileP = fopen($filepath, 'wb');
$imgCont = explode(',', $base64_img);
fwrite($fileP, base64_decode($imgCont[1]));
fclose($fileP);
}
# => $filepath <= This path will be stored as blob type in database.
# base64_decoded images will be written in folder too.
# Please don't forget to up vote if you like my solution. :)
I hope this will help you.
I solved this issue with core php method.
My solved code as below.
$base64string = 'BASE64 STRING GOES HERE';
$uploadpath = 'YOUR UPLOAD DIR PATH';
$parts = explode(";base64,", $base64string); //THIS WILL GET THE ORIGINAL FILE ENCODE STRING
$imagebase64 = base64_decode($parts[1]); //THIS WILL GET THE DECODED IMAGE STRING
$file = $uploadpath . uniqid() . '.png'; // THIS WILL GIVE THE FILE NAME AND SET THE FILE PATH
file_put_contents($file, $imagebase64); // THIS FUNCTION WILL STORE THE IMAGE TO GIVEN PATH WITH FILE_NAME

Categories