html2canvas.js not capturing image for dynamically generated content - javascript

I am using vivagraphs to generate dynamic svg element but when I click capture button, no nodes and edges are shown.
This is the script:
$(document).ready(function() {
//var testdiv = document.getElementById("testdiv");
$('#btn').click(function(){
html2canvas($("#graph1"), {
onrendered: function(canvas) {
var myImage = canvas.toDataURL("img/png");
window.open(myImage);
}
});
});
While I inspect for elements svg is shown after rendering graph but snapshot does not contain nodes and edges.
Is there an alternative for html2canvas or can I fix this issue?

if you want to save the image from canvas to some image format here is some help for you. hope this will help you out.
$(document).ready(function() {
$('#btn').click(function(){
html2canvas(document.getElementById('graph1'), {
onrendered: function(canvas) {
var cs = new CanvasSaver('save_img.php',canvas,'myimage')
}
});
});
});
here CanvasSaver() function define is here below which take three parameters one is a php file which process image from RAW date to some image format. i'll write the code of 'save_img.php' belwo this script part and save that file in your root directory.
function CanvasSaver(url, cnvs, fname) {
this.url = url;
if(!cnvs || !url) return;
fname = fname || 'picture';
var data = cnvs.toDataURL("image/png");
data = data.substr(data.indexOf(',') + 1).toString();
var dataInput = document.createElement("input") ;
dataInput.setAttribute("name", 'imgdata') ;
dataInput.setAttribute("value", data);
dataInput.setAttribute("type", "hidden");
var nameInput = document.createElement("input") ;
nameInput.setAttribute("name", 'name') ;
nameInput.setAttribute("value", fname + '.jpg');
var myForm = document.createElement("form");
myForm.method = 'post';
myForm.action = url;
myForm.appendChild(dataInput);
myForm.appendChild(nameInput);
document.body.appendChild(myForm) ;
myForm.submit() ;
document.body.removeChild(myForm) ;
}
in above script whatever the image formate you want to save from browser give that image extension in this function above script
nameInput.setAttribute("value", fname + '.jpg');
now here is the code for your 'save_img.php' and save it in your root directory.
<?php
# we are a PNG image
header('Content-type: image/png');
# we are an attachment (eg download), and we have a name
header('Content-Disposition: attachment; filename="' . $_POST['name'] .'"');
#capture, replace any spaces w/ plusses, and decode
$encoded = $_POST['imgdata'];
$encoded = str_replace(' ', '+', $encoded);
$decoded = base64_decode($encoded);
#write decoded data
echo $decoded;
?>

you maybe using beta version of lib , goto releases on github page of html2canvas and download stable alpha version

Related

Using jQuery/javascript to dynamically add all images in a directory [duplicate]

I have a folder named "images" in the same directory as my .js file. I want to load all the images from "images" folder into my html page using Jquery/Javascript.
Since, names of images are not some successive integers, how am I supposed to load these images?
Works both localhost and on live server without issues, and allows you to extend the delimited list of allowed file-extensions:
var folder = "images/";
$.ajax({
url : folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(jpe?g|png|gif)$/) ) {
$("body").append( "<img src='"+ folder + val +"'>" );
}
});
}
});
NOTICE
Apache server has Option Indexes turned on by default - if you use another server like i.e. Express for Node you could use this NPM package for the above to work: https://github.com/expressjs/serve-index
If the files you want to get listed are in /images than inside your server.js you could add something like:
const express = require('express');
const app = express();
const path = require('path');
// Allow assets directory listings
const serveIndex = require('serve-index');
app.use('/images', serveIndex(path.join(__dirname, '/images')));
Use :
var dir = "Src/themes/base/images/";
var fileextension = ".png";
$.ajax({
//This will retrieve the contents of the folder if the folder is configured as 'browsable'
url: dir,
success: function (data) {
//List all .png file names in the page
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location.host, "").replace("http://", "");
$("body").append("<img src='" + dir + filename + "'>");
});
}
});
If you have other extensions, you can make it an array and then go through that one by one using in_array().
P.s : The above source code is not tested.
This is the way to add more file extentions, in the example given by Roy M J in the top of this page.
var fileextension = [".png", ".jpg"];
$(data).find("a:contains(" + (fileextension[0]) + "), a:contains(" + (fileextension[1]) + ")").each(function () { // here comes the rest of the function made by Roy M J
In this example I have added more contains.
If interested in doing this without jQuery - here's a pure JS variant (from here) of the answer currently most upvoted:
var xhr = new XMLHttpRequest();
xhr.open("GET", "/img", true);
xhr.responseType = 'document';
xhr.onload = () => {
if (xhr.status === 200) {
var elements = xhr.response.getElementsByTagName("a");
for (x of elements) {
if ( x.href.match(/\.(jpe?g|png|gif)$/) ) {
let img = document.createElement("img");
img.src = x.href;
document.body.appendChild(img);
}
};
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
}
xhr.send()
Here is one way to do it. Involves doing a little PHP as well.
The PHP part:
$filenameArray = [];
$handle = opendir(dirname(realpath(__FILE__)).'/images/');
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
array_push($filenameArray, "images/$file");
}
}
echo json_encode($filenameArray);
The jQuery part:
$.ajax({
url: "getImages.php",
dataType: "json",
success: function (data) {
$.each(data, function(i,filename) {
$('#imageDiv').prepend('<img src="'+ filename +'"><br>');
});
}
});
So basically you do a PHP file to return you the list of image filenames as JSON, grab that JSON using an ajax call, and prepend/append them to the html. You would probably want to filter the files u grab from the folder.
Had some help on the php part from 1
$(document).ready(function(){
var dir = "test/"; // folder location
var fileextension = ".jpg"; // image format
var i = "1";
$(function imageloop(){
$("<img />").attr('src', dir + i + fileextension ).appendTo(".testing");
if (i==13){
alert('loaded');
}
else{
i++;
imageloop();
};
});
});
For this script, I have named my image files in a folder as 1.jpg, 2.jpg, 3.jpg, ... to 13.jpg.
You can change directory and file names as you wish.
Based on the answer of Roko C. Buljan, I have created this method which gets images from a folder and its subfolders . This might need some error handling but works fine for a simple folder structure.
var findImages = function(){
var parentDir = "./Resource/materials/";
var fileCrowler = function(data){
var titlestr = $(data).filter('title').text();
// "Directory listing for /Resource/materials/xxx"
var thisDirectory = titlestr.slice(titlestr.indexOf('/'), titlestr.length)
//List all image file names in the page
$(data).find("a").attr("href", function (i, filename) {
if( filename.match(/\.(jpe?g|png|gif)$/) ) {
var fileNameWOExtension = filename.slice(0, filename.lastIndexOf('.'))
var img_html = "<img src='{0}' id='{1}' alt='{2}' width='75' height='75' hspace='2' vspace='2' onclick='onImageSelection(this);'>".format(thisDirectory + filename, fileNameWOExtension, fileNameWOExtension);
$("#image_pane").append(img_html);
}
else{
$.ajax({
url: thisDirectory + filename,
success: fileCrowler
});
}
});}
$.ajax({
url: parentDir,
success: fileCrowler
});
}
This is the code that works for me, what I want is to list the images directly on my page so that you just have to put the directory where you can find the images for example -> dir = "images /"
I do a substring var pathName = filename.substring (filename.lastIndexOf ('/') + 1);
with which I make sure to just bring the name of the files listed and at the end I link my URL to publish it in the body
$ ("body"). append ($ ("<img src =" + dir + pathName + "> </ img>"));
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script src="jquery-1.6.3.min.js"></script>
<script>
var dir = "imagenes/";
var fileextension = ".jpg";
$.ajax({
//This will retrieve the contents of the folder if the folder is configured as 'browsable'
url: dir,
success: function (data) {
//Lsit all png file names in the page
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location.pathname, "").replace("http://", "");
var pathName = filename.substring(filename.lastIndexOf('/') + 1);
$("body").append($("<img src=" + dir + pathName + "></img>"));
console.log(dir+pathName);
});
}
});
</script>
</head>
<body>
<img src="1_1.jpg">
</body>
</html>
If, as in my case, you would like to load the images from a local folder on your own machine, then there is a simple way to do it with a very short Windows batch file. This uses the ability to send the output of any command to a file using > (to overwrite a file) and >> (to append to a file).
Potentially, you could output a list of filenames to a plain text file like this:
dir /B > filenames.txt
However, reading in a text file requires more faffing around, so I output a javascript file instead, which can then be loaded in your to create a global variable with all the filenames in it.
echo var g_FOLDER_CONTENTS = mlString(function() { /*! > folder_contents.js
dir /B images >> folder_contents.js
echo */}); >> folder_contents.js
The reason for the weird function with comment inside notation is to get around the limitation on multi-line strings in Javascript. The output of the dir command cannot be formatted to write a correct string, so I found a workaround here.
function mlString(f) {
return f.toString().
replace(/^[^\/]+\/\*!?/, '').
replace(/\*\/[^\/]+$/, '');
}
Add this in your main code before the generated javascript file is run, and then you will have a global variable called g_FOLDER_CONTENTS, which is a string containing the output from the dir command. This can then be tokenized and you'll have a list of filenames, with which you can do what you like.
var filenames = g_FOLDER_CONTENTS.match(/\S+/g);
Here's an example of it all put together: image_loader.zip
In the example, run.bat generates the Javascript file and opens index.html, so you needn't open index.html yourself.
NOTE: .bat is an executable type in Windows, so open them in a text editor before running if you are downloading from some random internet link like this one.
If you are running Linux or OSX, you can probably do something similar to the batch file and produce a correctly formatted javascript string without any of the mlString faff.
You can't do this automatically. Your JS can't see the files in the same directory as it.
Easiest is probably to give a list of those image names to your JavaScript.
Otherwise, you might be able to fetch a directory listing from the web server using JS and parse it to get the list of images.
In jQuery you can use Ajax to call a server-side script. The server-side script will find all the files in the folder and return them to your html file where you will need to process the returned information.
You can use the fs.readdir or fs.readdirSync methods to get the file names in the directory.
The difference between the two methods, is that the first one is asynchronous, so you have to provide a callback function that will be executed when the read process ends.
The second is synchronous, it will returns the file name array, but it will stop any further execution of your code until the read process ends.
After that you simply have to iterate through the names and using append function, add them to their appropriate locations. To check out how it works see HTML DOM and JS reference
Add the following script:
<script type="text/javascript">
function mlString(f) {
return f.toString().
replace(/^[^\/]+\/\*!?/, '');
replace(/\*\/[^\/]+$/, '');
}
function run_onload() {
console.log("Sample text for console");
var filenames = g_FOLDER_CONTENTS.match(/\S+/g);
var fragment = document.createDocumentFragment();
for (var i = 0; i < filenames.length; ++i) {
var extension = filenames[i].substring(filenames[i].length-3);
if (extension == "png" || extension == "jpg") {
var iDiv = document.createElement('div');
iDiv.id = 'images';
iDiv.className = 'item';
document.getElementById("image_div").appendChild(iDiv);
iDiv.appendChild(fragment);
var image = document.createElement("img");
image.className = "fancybox";
image.src = "images/" + filenames[i];
fragment.appendChild(image);
}
}
document.getElementById("images").appendChild(fragment);
}
</script>
then create a js file with the following:
var g_FOLDER_CONTENTS = mlString(function() { /*!
1.png
2.png
3.png
*/});
Using Chrome, searching for the images files in links (as proposed previously) didn't work as it is generating something like:
(...) i18nTemplate.process(document, loadTimeData);
</script>
<script>start("current directory...")</script>
<script>addRow("..","..",1,"170 B","10/2/15, 8:32:45 PM");</script>
<script>addRow("fotos-interessantes-11.jpg","fotos-interessantes-> 11.jpg",false,"","");</script>
Maybe the most reliable way is to do something like this:
var folder = "img/";
$.ajax({
url : folder,
success: function (data) {
var patt1 = /"([^"]*\.(jpe?g|png|gif))"/gi; // extract "*.jpeg" or "*.jpg" or "*.png" or "*.gif"
var result = data.match(patt1);
result = result.map(function(el) { return el.replace(/"/g, ""); }); // remove double quotes (") surrounding filename+extension // TODO: do this at regex!
var uniqueNames = []; // this array will help to remove duplicate images
$.each(result, function(i, el){
var el_url_encoded = encodeURIComponent(el); // avoid images with same name but converted to URL encoded
console.log("under analysis: " + el);
if($.inArray(el, uniqueNames) === -1 && $.inArray(el_url_encoded, uniqueNames) === -1){
console.log("adding " + el_url_encoded);
uniqueNames.push(el_url_encoded);
$("#slider").append( "<img src='" + el_url_encoded +"' alt=''>" ); // finaly add to HTML
} else{ console.log(el_url_encoded + " already in!"); }
});
},
error: function(xhr, textStatus, err) {
alert('Error: here we go...');
alert(textStatus);
alert(err);
alert("readyState: "+xhr.readyState+"\n xhrStatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

how to make javascript in to PHP

I have the following javascript code which I need to be executed in a PHP file.
I need to know how should I enter the php tags to this javascript code.
I am new to web programming.
The javascript used here is to export content in the html page to a .csv file.
<!-- Scripts ----------------------------------------------------------- -->
<script type='text/javascript' src='https://code.jquery.com/jquery-
1.11.0.min.js'></script>
<!-- If you want to use jquery 2+: https://code.jquery.com/jquery-2.1.0.min.js -->
<script type='text/javascript'>
$(document).ready(function () {
console.log("HELLO")
function exportTableToCSV($table, filename) {
var $headers = $table.find('tr:has(th)')
,$rows = $table.find('tr:has(td)')
// Temporary delimiter characters unlikely to be typed by
keyboard
// This is to avoid accidentally splitting the actual
contents
,tmpColDelim = String.fromCharCode(11) // vertical tab
character
,tmpRowDelim = String.fromCharCode(0) // null character
// actual delimiter characters for CSV format
,colDelim = '","'
,rowDelim = '"\r\n"';
// Grab text from table into CSV formatted string
var csv = '"';
csv += formatRows($headers.map(grabRow));
csv += rowDelim;
csv += formatRows($rows.map(grabRow)) + '"';
// Data URI
var csvData = 'data:application/csv;charset=utf-8,' +
encodeURIComponent(csv);
// For IE (tested 10+)
if (window.navigator.msSaveOrOpenBlob) {
var blob = new Blob([decodeURIComponent(encodeURI(csv))], {
type: "text/csv;charset=utf-8;"
});
navigator.msSaveBlob(blob, filename);
} else {
$(this)
.attr({
'download': filename
,'href': csvData
//,'target' : '_blank' //if you want it to open in a
new window
});
}
//------------------------------------------------------------
// Helper Functions
//------------------------------------------------------------
// Format the output so it has the appropriate delimiters
function formatRows(rows){
return rows.get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim);
}
// Grab and format a row from the table
function grabRow(i,row){
var $row = $(row);
//for some reason $cols = $row.find('td') || $row.find('th')
won't work...
var $cols = $row.find('td');
if(!$cols.length) $cols = $row.find('th');
return $cols.map(grabCol)
.get().join(tmpColDelim);
}
// Grab and format a column from the table
function grabCol(j,col){
var $col = $(col),
$text = $col.text();
return $text.replace('"', '""'); // escape double quotes
}
}
// This must be a hyperlink
$("#export").click(function (event) {
// var outputFile = 'export'
var outputFile = window.prompt("What do you want to name your
output file (Note: This won't have any effect on Safari)") ||
'export';
outputFile = outputFile.replace('.csv','') + '.csv'
// CSV
exportTableToCSV.apply(this, [$('#dvData > table'),
outputFile]);
// IF CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
};
</script>
use this, add ?> before it and <?php after script
<?php
/* your php code */
?>
<script type='text/javascript'>
// your script
</script>
<?php
/* your php code */
?>
Top answer from a previous question
<script type="text/javascript">
var my_var = <?php echo json_encode($my_var); ?>;
</script>
works if you define and use the variable in PHP, and want to pass the variable in the Javascript.
If you are running in a PHP file (which you are) you can also use
function foo()
{
var i = 0 ;
i = <?php echo $my_var; ?>
}

Passing an image file from php to javascript

I have a database in which there are images stored as LONGBLOB files. It seems I can't figure out how to "transport" those images to JS file so I could check their dimensions and compare them with the dimensions of the screen. Here is how I donwload the images:
function fillArrays(){
$idArray = array();
$sql = "SELECT oglas_id,slika,prioriteta FROM deska WHERE deska.datumz <= CURRENT_DATE AND deska.datumk >= CURRENT_DATE;";
$result = mysqli_query($GLOBALS['conn'],$sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck>0){
while($row = mysqli_fetch_assoc($result)){
array_push($GLOBALS['idArray'],$row['oglas_id']);
$image = base64_encode($row['slika']); // THIS "slika" means "image" in my lang...
array_push($GLOBALS['imgArray'],$image); //AND THIS
array_push($GLOBALS['prArray'],$row['prioriteta']);
}
}else{
die("Oops there seems to be an error(arr)");
}
}
I am preety sure everything in lines of SQL is correct. The problem begins when I try to get the images stored in array into javascript. I am trying to do it by json_encode.
<script>
var idArray = <?php echo json_encode($idArray) ?>;
var imgArray = <?php echo json_encode($imgArray) ?>;
var prArray = <?php echo json_encode($prArray) ?>;
</script>
<script src="includes/script.js"></script>
Then we jump to my javascript file ( script.js ). Now when I try to output the dimensions of the image selected, it says undefined undefined (width*height).
Here is how I try to obrain the info of the image selected.
in my JS file:
var imgArray = window.imgArray;
var img = new Image();
img = imgArray[0];
img.width;
img.height;
I am aware the questions has been asked many times but I can't seem to wrap my head around it so I figured I would supply you guys with my concrete problem.
Thanks to anyone who helps.
Since I dont think people fully understand:
Aim of the site:
Download images from database.
Resize them.(IMAGE CANNOT BE LARGER THAN HALF OF THE SCREEN SIZE)
Place them in the 2x2 table.
You need to wait for the loaded image.
img.onload = function () {
alert(this.width + ' ' + this.height);
};
Btw, if you need to resize the image, why don't you pass the screen resolution to PHP and then, there, you do all your checks? It's easier, because if you do this from JS, it depends on user browser.
Code for reading image data :
function readURL(input) {
console.log(input.files);
if (input.files && input.files[0]) {
var reader = new FileReader();
//alert(input.files[0]);
reader.onload = function (e) {
$('#image_source').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
Convert the fetched image to base64 :
var handleFileSelect = function(evt) {
var files = evt.target.files;
var file = files[0];
if (files && file) {
var reader = new FileReader();
reader.onload = function(readerEvt) {
var binaryString = readerEvt.target.result;
document.getElementById("hidden_id").value = btoa(binaryString);
};
reader.readAsBinaryString(file);
}
};
Add listener for image input type :
if (window.File && window.FileReader && window.FileList && window.Blob) {
document.getElementById('image_id').addEventListener('change', handleFileSelect, false);
} else {
alert('The File APIs are not fully supported in this browser.');
}
Hope it helps you.

Output image to browser before saving it to the folder

I've created a functionality on my website where user's can change the background image via upload. The procedure is following:
User goes to settings page and selects an image file to be uploaded. After selecting image, the browser will output it so that user can preview
it before actually saving it's file to in to the folder and filepath in to the database. After that, if user is happy with the result, he can save it to the
folder by pressing "Upload Background Image" button.
All of the above is handled with AJAX.
I am having trouble to just output the image to the browser without actually saving it twice, first into tests folder and after that into backgrounds folder.
I'm using CodeIgniter as my backend framework and jQuery for my AJAX requests.
Here are my methods for outputting (testing) and saving the image:
public function test_image()
{
if($this->input->is_ajax_request())
{
// This part of code needs to be replaced to only just output the image (return it as a JSON), not actually saving it to another a folder
$ext = pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
$new_img_name = random_string('unique'). "." . $ext;
$config['upload_path'] = './public/images/uploads/tests';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1000000';
$config['max_width'] = '2000';
$config['max_height'] = '1600';
$config['file_name'] = $new_img_name;
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
$this->output->set_content_type('application_json');
$this->output->set_output(json_encode(array('image_errors' => $this->upload->display_errors('<p class="text-center">','</p>'))));
return false;
} else {
$this->output->set_content_type('application_json');
$this->output->set_output(json_encode(array('userfile' => $new_img_name)));
}
} else {
echo "Not an ajax request";
}
}
// This method works properly
public function upload_background_image()
{
if (isset($_POST))
{
$ext = pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
$new_img_name = random_string('unique'). "." . $ext;
$config['upload_path'] = './public/images/uploads/backgrounds';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1000000';
$config['max_width'] = '2000';
$config['max_height'] = '1600';
$config['file_name'] = $new_img_name;
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
$this->output->set_content_type('application_json');
$this->output->set_output(json_encode(array('image_errors' => $this->upload->display_errors('<p class="text-center">','</p>'))));
return false;
} else {
$this->load->model('user_model');
$user_id = $this->session->userdata('user_id');
$upload_photo = $this->user_model->updateUserInfo($user_id, ['body_background_url' => $new_img_name]);
if ($upload_photo === true) {
$this->session->set_userdata(['body_background_url' => $new_img_name]);
redirect(base_url());
}
}
}
}
And here's my AJAX:
$("#bg-cover-file").change(function(e) {
e.preventDefault();
var form = $(this).closest('form');
form.ajaxSubmit({
dataType: 'json',
beforeSubmit: function() {
},
success: function(response) {
if(response.userfile) {
// Output the image
$('.test-image').attr('src', response.userfile);
$('span.file-input').hide();
// Change the form action attribute
var new_path = 'uploads/upload_background_image';
form.attr('action', new_path);
} else {
$('#error-modal').modal('show');
$("#error-body").html(response.image_errors);
return false;
}
}
});
return false;
});
--Working Demo--
I have put comments in this demo to explain what the steps are so please read them.
If you don't understand anything in this answer please leave a comment below and i will update the answer until you understand line for line. You don't learn from copy/paste so please be sure to understand the answer.
function MyFunction() {
var img=document.getElementById('BackgroundImage');
var Status=document.getElementById('Status');
var savebtn=document.getElementById('savebtn');
/* SetBG will target the body tag of the web page.
You can change this to any element -
var SetBG=document.getElementById('YourID').style;
*/
var SetBG=document.body.style;
//Split the image name
var fileExt=img.value.split('.');
//Use the last array from the split and put to lowercase
var fileformat=fileExt[fileExt.length -1].toLowerCase();
// Check the file extension (Image formats only!)
if((fileformat==='jpg')||(fileformat==='gif')||(fileformat==='png')||(fileformat==='jpeg')) {
if (img.files && img.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
//----Image is ready for preview.
SetBG.background='url('+e.target.result+') no-repeat center center fixed';
/*---- Optional, Set background as cover ---*/
SetBG.backgroundSize="cover";
SetBG.OBackgroundSize="cover";
SetBG.webkitBackgroundSize="cover";
//--Hide Loading Message
Status.style.display="none";
//----- Display (Save/Upload button?)
savebtn.style.display="block";
}
/*-------Reading File....
Display a message or loading gif for large images to be processed?
*/
Status.innerHTML="Loading...";
Status.style.display="block";
savebtn.style.display="none";
reader.readAsDataURL(img.files[0]);
}
}else{
/*----User file input not accepted (File isn't jpg/gif/png/jpeg)
Empty the input element and set the background to default.
*/
Status.innerHTML="Format not accepted";
Status.style.display="block";
savebtn.style.display="none";
SetBG.background='white';
document.getElementById('BackgroundImage').value='';
}
}
#Status{display:none;background:white;color:black;font-size:16pt;}
#savebtn{display:none;}
<div id="Status"></div>
<input type="file" id="BackgroundImage" onchange="MyFunction()"/>
<button id="savebtn" onclick="alert('Now upload the image');">Upload and save</button>
I hope this helps. Happy coding!
This may help you
let assume your browse button's id is bg-cover-file and the id of the image tag where you want to display the image preview_image
$(document).on("change", "#bg-cover-file", function(event)
{
if (this.files && this.files[0])
{
var reader = new FileReader();
reader.onload = function (e)
{
$('#preview_image').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
});
function MyFunction() {
var img=document.getElementById('BackgroundImage');
var Status=document.getElementById('Status');
var savebtn=document.getElementById('savebtn');
/* SetBG will target the body tag of the web page.
You can change this to any element -
var SetBG=document.getElementById('YourID').style;
*/
var SetBG=document.body.style;
//Split the image name
var fileExt=img.value.split('.');
//Use the last array from the split and put to lowercase
var fileformat=fileExt[fileExt.length -1].toLowerCase();
// Check the file extension (Image formats only!)
if((fileformat==='jpg')||(fileformat==='gif')||(fileformat==='png')||(fileformat==='jpeg')) {
if (img.files && img.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
//----Image is ready for preview.
SetBG.background='url('+e.target.result+') no-repeat center center fixed';
/*---- Optional, Set background as cover ---*/
SetBG.backgroundSize="cover";
SetBG.OBackgroundSize="cover";
SetBG.webkitBackgroundSize="cover";
//--Hide Loading Message
Status.style.display="none";
//----- Display (Save/Upload button?)
savebtn.style.display="block";
}
/*-------Reading File....
Display a message or loading gif for large images to be processed?
*/
Status.innerHTML="Loading...";
Status.style.display="block";
savebtn.style.display="none";
reader.readAsDataURL(img.files[0]);
}
}else{
/*----User file input not accepted (File isn't jpg/gif/png/jpeg)
Empty the input element and set the background to default.
*/
Status.innerHTML="Format not accepted";
Status.style.display="block";
savebtn.style.display="none";
SetBG.background='white';
document.getElementById('BackgroundImage').value='';
}
}
#Status{display:none;background:white;color:black;font-size:16pt;}
#savebtn{display:none;}
<div id="Status"></div>
<input type="file" id="BackgroundImage" onchange="MyFunction()"/>
<button id="savebtn" onclick="alert('Now upload the image');">Upload and save</button>

HTML5 URL to saved image displays previously created image when clicked

I have an HTML5 app that saves the canvas image to the server and then provides a link to that image that opens in a new window.
This works fine the first time I save it, but if I create and save a new image and then click on the link it displays the old image that was previously created.
Clicking on refresh will force it to display the new one, but I was wondering if there is a way to make sure it displays the correct image so that I don't have to refresh the page?
Below is what I am using to save the image.
<script>
function saveImageAs (imgOrURL) {
if (typeof imgOrURL == 'object')
imgOrURL = imgOrURL.src;
window.win = open (imgOrURL);
setTimeout('win.document.execCommand("SaveAs")', 500);
}
</script>
<script type="text/javascript">
//****************************************************************
// Save canvas content into image file. //
//****************************************************************
function saveViaAJAX()
{
document.getElementById('saveimage').style.visibility="hidden";
document.getElementById("debugFilenameConsole").innerHTML="Please wait while your image is been generated";
var testCanvas = document.getElementById('canvas');
var canvasData = testCanvas.toDataURL("image/jpg");
var postData = "canvasData="+canvasData;
var debugConsole= document.getElementById("debugConsole");
debugConsole.value=canvasData;
//alert("canvasData ="+canvasData );
var ajax = new XMLHttpRequest();
ajax.open("POST",'savecanvas.php',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
//ajax.setRequestHeader('Content-TypeLength', postData.length);
ajax.onreadystatechange=function()
{
if (ajax.readyState == 4)
{
//alert(ajax.responseText);
// Write out the filename.
document.getElementById("debugFilenameConsole").innerHTML="Saved as <a target='_blank' href='myimage.php'> MyImage.jpg"+ajax.responseText+"</a><br>Reload this page to start a new image or click on the link above to open the file.";
}
}
ajax.send(postData);
}
</script>
And the PHP
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
//echo "unencodedData".$unencodedData;
// Save file. This example uses a hard coded filename for testing,
// but a real application can specify filename in POST variable
$fp = fopen( 'MyImage.jpg', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
}
header("Content-Type: image/jpg");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment; filename=MyImage.jpg");
imagejpeg($img, null, 100);
?>
Because you are giving the image the same name and path, the browser is helpfully caching it for you.
Use a unique path to avoid this!
You can try
var random=new Date();
var random2=getTime();
var rand=random+random2;
imgOrURL = imgOrURL.src+'?rnd='+rand
or for PHP
$rand=rand();
MyImage.php?rand=<?=$rand?>
or
$image='MyImage.php?rand='.$rand.'';
For future use, to save headache. Add dates and times first because using md5 , sha1() or a rand() or JavaScript unique key can be a nightmare, example:
/// This is much cleaner
/11.1.2012/11.05/eachier93.jpg
/11.1.2012/11.05/4358390485/93.jpg
/11.1.2012/11.10/3249203489834/234234.jpg
/// then this
/files/342748234234234/234982348394/333535.jpg
/files/4535345345/234234234234/3332.jpg
/files/23423434324/023840348234/2343.jpg

Categories