replace php script with javascript or jquery to decode base64 - javascript

I use the following code to save my canvas to the server as an png:
Now, I want to replace the php with js or jquery but I have no idea to do this with base64 decoding.
Folder: imgs
HTML:
Link with id="save" to open a thumbnail with download-link
Javascript:
$("#save").click(function () {
$("#result").html("<img src=" + d.toDataURL() + ' /><br /><a href="#" id="get" class="minimal" >Download This</a>');
$("#data").val(d.toDataURL());
$("#get").click(function () {
$("#frm").trigger("submit")
})
});
$("#clear").click(function () {
e.fillStyle = "#fff";
e.fillRect(0, 0, d.width, d.height);
e.strokeStyle = "red";
e.fillStyle = "red"
})
})
function saveRestorePoint() {
var oCanvas = document.getElementById("can");
var imgSrc = oCanvas.toDataURL("image/png");
restorePoints.push(imgSrc);
}
PHP:
<?php
if (isset($_POST['data'])) {
$data = $_POST['data'];
//removing the "data:image/png;base64," part
$uri = substr($data, strpos($data, ",") + 1);
$filenamex = time();
$filename = 'imgs/' . $filenamex . '.png';
// put the data to a file
file_put_contents($filename, base64_decode($uri));
///*
//force user to download the image
if (file_exists($filename)) {
// We'll be outputting a PNG
header('Content-type: image/png');
// It will be called wow.png
header('Content-Disposition: attachment; filename="' . $filename . '"');
// The PDF source is in wow.png
readfile($filename);
exit();
}
}
?>

Related

How to Show result after uploaded file in PHP

I have a script that uploads the video to a server, everything is correct but there is a problem, after the upload of the video to the server is completed
it shows all the uploaded files in the (uploads) folder as array!
I only want the result of the file I just uploaded, and it doesn't show me the previous files!
I need ffmpeg to improve video quality
index.php
<?php
//index.php
?>
<!DOCTYPE html>
<html>
<head>
<title>Personal Video Uploader</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.js"></script>
<link rel="stylesheet" href="css/main.css">
</head>
<body class="bg-body">
<div class="container">
<form action="upload.php" class="dropzone font" id="dropzoneFrom">
</form>
</form>
<br />
<div id="preview"></div>
<br />
</div>
</body>
</html>
<script>
$(document).ready(function(){
Dropzone.options.dropzoneFrom = {
autoProcessQueue: true,
timeout: 300000,
acceptedFiles:"video/*",
init: function(){
var submitButton = document.querySelector('#submit-all');
myDropzone = this;
submitButton.addEventListener("click", function(){
myDropzone.processQueue();
});
this.on("complete", function(){
if(this.getQueuedFiles().length == 0 && this.getUploadingFiles().length == 0)
{
var _this = this;
_this.removeAllFiles();
}
list_image();
});
},
};
list_image();
function list_image()
{
$.ajax({
url:"upload.php",
success:function(data){
$("#preview").html(data);
}
});
}
$(document).on('click', '.remove_image', function(){
var name = $(this).attr('id');
$.ajax({
url:"upload.php",
method:"POST",
data:{name:name},
success:function(data)
{
list_image();
}
})
});
});
</script>
upload.php
<?php
//upload.php
$folder_name = 'upload/';
$tumb_name = 'thumb/';
$imageext = '.png';
if(!empty($_FILES))
{
$temp_file = $_FILES['file']['tmp_name'];
$location = $folder_name . $_FILES['file']['name'];
move_uploaded_file($temp_file, $location);
$upload = $_FILES['file']['name'];
$uploadStr = str_replace(" ", "\ ",$upload);
$locationStr = str_replace(" ","\ ",$location);
$cmd = "ffmpeg -y -i {$locationStr} -ss 00:00:15 -vframes 1 thumb/{$uploadStr}.png 2>&1";
echo shell_exec($cmd);
}
if(isset($_POST["name"]))
{
$filename = $folder_name.$_POST["name"];
$imagename = $thumb_name.$_POST["name"].$imageext;
unlink($filename);
unlink($imagename);
}
$result = array();
$files = scandir('upload');
$output = '<div class="row">';
if(false !== $files)
{
foreach($files as $file)
{
if('.' != $file && '..' != $file)
{
$output .= '
<img src="thumb/'.$file.'.png" class="img-thumbnail" width="246px" height="138px" style="height:138px;" />
<button type="button" class="btn btn-link remove_image" id="'.$file.'">Remove</button>
';
}
}
}
$output .= '</div>';
echo $output;
?>
EDIT:
I put the example on an Array, I don't want it, I just want it to show the downloaded video I just uploaded as a result.
EDIT 2 :
There are some who say type $location and it displays the downloaded file, but this does not work!!!
I just tried more than once and with several uses, there is no display where the text is empty
This is an example of that
<?php
//upload.php
$folder_name = 'upload/';
$tumb_name = 'thumb/';
$imageext = '.png';
if(!empty($_FILES))
{
$temp_file = $_FILES['file']['tmp_name'];
$location = $folder_name . $_FILES['file']['name'];
move_uploaded_file($temp_file, $location);
$upload = $_FILES['file']['name'];
$uploadStr = str_replace(" ", "\ ",$upload);
$locationStr = str_replace(" ","\ ",$location);
$cmd = "ffmpeg -y -i {$locationStr} -ss 00:00:15 -vframes 1 thumb/{$uploadStr}.png 2>&1";
echo shell_exec($cmd);
}
if(isset($_POST["name"]))
{
$filename = $folder_name.$_POST["name"];
$imagename = $thumb_name.$_POST["name"].$imageext;
unlink($filename);
unlink($imagename);
}
$output .= 'Successfly file is "'.$location.'"';
echo $output;
?>
Result : Successfly file is ""
no name file :(
EDIT 3 :
this code upload.php
functions not working
<?php
//upload.php
$folder_name = 'upload/';
$tumb_name = 'thumb/';
$imageext = '.png';
if(!empty($_FILES))
{
$temp_file = $_FILES['file']['tmp_name'];
$location = $folder_name . $_FILES['file']['name'];
move_uploaded_file($temp_file, $location);
$upload = $_FILES['file']['name'];
$uploadStr = str_replace(" ", "\ ",$upload);
$locationStr = str_replace(" ","\ ",$location);
$cmd = "ffmpeg -y -i {$locationStr} -ss 00:00:15 -vframes 1 thumb/{$uploadStr}.png 2>&1";
echo shell_exec($cmd);
}
echo "The file " . $location . " has been uploaded";
// not working
echo "<br>";
echo "The file " . $upload . " has been uploaded";
// not working
echo "<br>";
echo "The file " . $uploadStr . " has been uploaded";
// not working
echo "<br>";
echo "The file " . $locationStr . " has been uploaded";
// not working
?>
this error:
[23-Apr-2022 12:31:56 Asia/Riyadh] PHP Notice: Undefined variable: location in /home/prdix/public_html/test/upload.php on line 38
line 38: echo $location;
About the developer solution Markus AO
I did the experiment and it is quite good, but dropzone is still missing, because I will upload a large video and the normal upload compresses the video before uploading, here is a picture from my mobile while uploading, but this does not happen with dropzone
I want to implement this in dropzone as well, because this library does not compress the video, but upload it in full size.
Thank you bro.

Issue with html2canvas

I need to have the child image appear in a new division it places it outside the HTML tag and cuts off bottom on save any suggestions?
I was able to get Clone to work TY for that advise... But my upload is still missing app. 50 pixels from bottom of image ..... Still have not figured out how to return the image URL back and would like to get the clone to appear Directly under my generated image and not off page..... any advise on that?
function screenshot(){
html2canvas(document.getElementById("capture")).then(function(canvas) {
var elmnt = document.getElementsByTagName("DIV")[2];
var cln = elmnt.cloneNode(true);
document.body.appendChild(cln);
// Get base64URL
var base64URL = canvas.toDataURL('image/jpg').replace('image/jpg', 'image/octet-stream');
// AJAX request
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {image: base64URL},
success: function(data){
console.log('Upload successfully.');
}
});
});
}
Here is my ajaxfile
$image = $_POST['image'];
$location = "upload/";
$image_parts = explode(";base64,", $image);
$image_base64 = base64_decode($image_parts[1]);
date_default_timezone_set("America/Chicago");
$filename = date("m_j_y-H_i_s").'.png';
$file = $location . $filename;
$imageurl = 'upload/'.$filename.'.png';
file_put_contents($file, $image_base64);
echo $filename;
echo $file;
echo $location;
echo $image;

Upload an Image using Ajax and PHP

I want to upload an image when the user clicks a button(#myid.save).Below is my code:
HTML Code:
<canvas id="cnv" width="500" height="100"></canvas>
<input id="myid_save" type="submit">Save</input>
JavaScript Code:
$('#myid_save').on('click', function(e) {
e.preventDefault();
saveViaAJAX();
});
function saveViaAJAX()
{
var testCanvas = document.getElementById("cnv");
var canvasData = testCanvas.toDataURL("image/png");
//var postData = "canvasData="+canvasData;
$.ajax({
type: "POST",
url: "testSave.php",
data: {
imgBase64: canvasData
}
}).done(function(o) {
console.log('saved');
});
}
testSave.php File:
<?php
define('UPLOAD_DIR', 'C:\xampp\htdocs\drupal-7.34\sites\all\modules\myid\uploads\id_signature');
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . '\sample.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
My console says "saved" but there's no image saved in my server. Where am I missing?
testSave.php references $_POST['canvasData'], but the JS sends the intended variable as imgBase64. That line should instead read $img = $_POST['imgBase64'] in order to match the AJAX.

Call the canvas image to another div or page

Can anybody help me with this I'm solving this problem for almost a week and never get success. I want to happen is to call the image that was been created the image goes to "image" in a div and I want to call that image to the another page but No image show. Please take a look my code.
<script>
function myFunction(){
html2canvas([document.getElementById('card-container')], {
onrendered: function (canvas) {
var data = canvas.toDataURL('image/png');
// AJAX call to send `data` to a PHP file that creates an image from the dataURI string and saves it to a directory on the server
var image = new Image();
image.src = data;
document.getElementById('image').appendChild(image);
}
});
}
</script>
<button onclick="myFunction()" >Try it</button>
<div id="image">
<p>Image:</p>
</div>
<form enctype="multipart/form-data" action="sample.com" method="post" onsubmit="this.divcontent.value = document.getElementById('image').innerHTML;" >
<input type="hidden" name="image" id="divcontent" value="" />
<input type="submit" value="Submit" />
</form>
Here is the ready-image.php
<?php
$img = $_POST['divcontent'];
echo "<img src='$img' alt='image' />";
define('UPLOAD_DIR', 'wp-content/uploads/2014/03/');
$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.';
?>
Please help me guys. Thank you very much.
I am not sure if this is what you want. Since the ajax part is missing from your code, I am just trying to pass the image captured to the ready-image.php and display it.
I am assuming that the codes are on 2 separate files.
<script>
function myFunction() {
html2canvas([document.getElementById('card-container')], {
onrendered: function (canvas) {
var data = canvas.toDataURL('image/png');
var image = new Image();
image.src = data;
document.getElementById('image').appendChild(image);
$("#divcontent").val(data); //save the image base64 string to a hidden input
}
});
}
</script>
<div id="card-container">
<button onclick="myFunction()" >Try it</button>
<div id="image">
<p>Image:</p>
</div>
<form action="ready-image.php" method="POST">
<input type="hidden" name="divcontent" id="divcontent" />
<input type="submit" value="Submit" />
</form>
</div>
ready-image.php:
<?php
$img = $_POST['divcontent'];
echo "<img src='$img' alt='image' />";
define('UPLOAD_DIR', 'wp-content/uploads/2014/03/');
$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.';
?>
Update:
<?php
$img = $_POST['divcontent'];
echo "<img src='$img' alt='image' />";
define('UPLOAD_DIR', 'wp-content/uploads/2014/03/');
$filteredData = substr($img, strpos($img, ",") + 1);
$decodedData = base64_decode($filteredData);
$file = UPLOAD_DIR . uniqid() . '.png';
$fp = fopen($file,'wb');
if ($fp) {
fwrite($fp, $decodedData);
print $file;
} else {
print 'Unable to save the file.';
}
fclose($fp);
?>
I commented out the download part because I am not sure how exactly you call the ajax to save the file, so that part is omitted from my solution.

Upload Image Using Ajax and PHP and Return Uploaded Image URL

I am trying to upload image without refresh but i don't have much knowledge about ajax.
I have php file thy return image url when i submit post with ajax function.
Javascript
$(document).ready(function() {
$('#photoimg').live('change', function() {
$("#preview").html('');
$("#preview").html('<img src="loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm({
target: '#preview'
}
}).submit();
});
});
PHP
<?php
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$imge1="uploads/".$actual_image_name;
echo $imge1;
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>
HTML
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload your image <input type="file" name="photoimg" id="photoimg" />
</form>
<div id='preview'>
</div>
<img src = "" id="thumb_img" />
Now result is image url. when image select ajax automatically post sand to php.Php save image and return url and this url show in target div.So now i need this url set as background url. Like image select target div background change.
I would just do something like:
$('#myForm').ajaxForm(function(url) {
$('#preview').css('background-image', "url(" + url + ")");
});

Categories