get the file name from base64_decode image - php

Image will send from mobile api with base64 type and I am trying to get the image name from base64_decoded image file.how can I get it?
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);
$im = imagecreatefromstring($data);
here is my fuction trying to get image name written with laravel
public function completeProfile($session_id,$username,$fullname,$position,$image){
$user = JWTAuth::toUser($session_id);
$userid = $user->id;
$img = base64_decode($image);
if(file_put_contents(public_path().'/images/users',$img)){
$result = $this->repository->completeProfile($userid,$username,$fullname,$position,$image);
}
return false;
}

I have used this code in slim php framwork to save image to desired folder
$img= base64_decode($val_pic);
$image_name= "test.jpg"; /* name image*/
if( $file = fopen("folder/".$image_name, 'wb')){
fwrite($file, $img);
fclose($file);
}

It is not possible to get the filename from base64 format, as this only contains the data that makes up the image, not it's metadata.

Related

file_put_contents() or similar to create new photo

I receive a string of base64 and am able to decode it and put it into a file. The problem is, I would like to create a new image file each time to put this base64 into.
Currently I have a basic code which is able to put contents into the file that is pre-existing but the current code does not create a non-existent file.
$data = base64_decode($data);
$path = 'abc';
var_dump(is_dir($path));
if ( ! is_dir($path)) {
if(mkdir($path, 0777)) {
echo "created dir";
}
}
file_put_contents('tmp.png', $data);
Base64 function to decode
function base64ToFile($base64String, $outputFile) {
$file = fopen($outputFile, "wb");
$data = explode(',', $base64String);
fwrite($file, base64_decode($data[1]));
fclose($file);
return $outputFile;
}
Check this the function will return you the unique name after uploading your image in a directory
$imageBase64=$_POST['image_converted_base64'];//get base64 of image from client end
$unique_name =uploadSingleImage($imageBase64);//function call
//function to upload image and get an unique name to store in db
function uploadSingleImage($base64) {
$uniname = uniqid() . date("Y-m-d-H-i-s") . ".png";
$new_image_url = "../../image/" . $uniname;
$base64 = 'data:image/jpeg;base64,' . $base64;
$base64 = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $base64));
file_put_contents($new_image_url, $base64);
return $uniname;
}

=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

saving canvas in php but no data in image file

Following code i am trying to save canvas on my Machine . in folder image file is created but it is of 0kb .
on click of download button i am setting value in text and on next php page i am reading value with $_POST['img_name']; .
JQuery ::
$("#Download").click(function() {
console.log('Download clicked');
//alert('Download clicked');
var myval = canvas.toDataURL();
$('#img_txt').val(myval);
});
php code ::
<?php
$myval = $_POST['img_name'];
echo "string is ".$myval;
?>
<?php
$data = base64_decode($_POST['img_name']);
/* Name the file anything you want */
$filename = 'my_image.png';
/* Remove 1st line of base64 string */
/* Note: replace '$base64' with your own variable */
$img = str_replace('data:image/png;base64,', '', $data);
/* Replace spaces */
$img = str_replace(' ', '+', $img);
/* Decode string */
$data = base64_decode($img);
/* Full path to upload directory with at the end the filename */
$file = 'D:/upload/'.$filename;
/* Save, make sure the directory is writeable! */
file_put_contents($file, $data);
?>
I have check $_POST['img_name'] i am getting base64 string ? what is the problem in my code?
Replace upload.php file
if ( isset($_POST["image"]) && !empty($_POST["image"]) ) {
// get the image data
$data = $_POST['image'];
// remove the prefix
$uri = substr($data,strpos($data,",")+1);
// create a filename for the new image
$file = md5(uniqid()) . '.png';
// decode the image data and save it to file
file_put_contents($file, base64_decode($uri));
// return the filename
echo $file;
}
Your jQuery isn't sending anything to your .php
Try this:
// convert the canvas to base64 data
var dataURL=canvas.toDataURL();
// call upload.php and post the data
$.ajax({
type: "POST",
url: "upload.php",
data: {image: dataURL}
}).done(function( respond ) {
console.log("Saved filename: "+respond);
});
Your upload file should remove the datatype prefix before decoding.
Try this for upload.php:
<?php
if ( isset($_POST["image"]) && !empty($_POST["image"]) ) {
// get the image data
$data = $_POST['image'];
// remove the prefix
$uri = substr($data,strpos($data,",") 1);
// create a filename for the new image
$file = md5(uniqid()) . '.png';
// decode the image data and save it to file
file_put_contents($file, base64_decode($uri));
// return the filename
echo $file;
}
Also, make sure your php server is configured:
Assign an upload directory
Give write permission to the upload directory
I used Following code to save base64 as an image,
<?php
if (isset($_POST["image"]) && !empty($_POST["image"])) {
// get the image data
$data = $_POST['image'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
//Image name
// $filename ="image". md5(uniqid()) . '.png';
$filename = "Post_Card.png";
$file = '../ReportCard/' . $filename;
// decode the image data and save it to file
file_put_contents($file, $data);
echo $file;
}
?>
If require we can use following code to give random generated names to file ,
// create a filename for the new image
$file = md5(uniqid()) . '.png';
Are you sure it is a png format?
because when you run the method toDataURL(); the default is PNG you cant try toDataURL("image/jpeg"); or any other format that correspond wit your need.
And you might want to consider uploading it to PHP so you can save it on your server in a directory let's say Pics.

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