how to pass Image data uri from javascript to php - javascript

I have a webpage which displays a chart. I had to generate a pdf of this chart. So I wrote this code to capture the chart as an image and put inside the pdf. I used html2canvas for this which generated a data uri for the image. Now I am stuck with this uri in javascript. The pdf code is a php script which needs this uri. How do I do this ?
The chart.php generates the chart and using html2canvas stores the image datatauri into localstorage.
CHART.PHP
<script>
//<![CDATA[
(function() {
window.onload = function(){
html2canvas(document.getElementById('chart'), {
"onrendered": function(canvas) {
var img = new Image();
img.onload = function() {
img.onload = null;
console.log(canvas.toDataURL("image/png"));
window.localStorage.setItem("imgURL", canvas.toDataURL("image/png"));
};
img.onerror = function() {
img.onerror = null;
if(window.console.log) {
window.console.log("Not loaded image from canvas.toDataURL");
} else {
//alert("Not loaded image from canvas.toDataURL");
}
};
img.src = canvas.toDataURL("image/png");
}
});
};
})();
//]]>
</script>
<body>
<a href="pdfGen.php" id="download" >Report</a>
</body>
This is the php script which generates the pdf using fpdf library
pdfGen.php
<?php
/*$pdf = new FPDF();
$pdf->AddPage();
//over here I want to add the image from the chart.php page whose data url is now in the localstorage.
..more code to generate report
$pdf->output();*/
?>
How do i send the such a big uri to this php script ? Trying an ajax wont work as I need to redirect to this php page. Also sending the uri along in the url wont work either as the url becomes too large and goes beyond its capacity.

In your script :
<script>
document.getElementById('imageURL').value=canvas.toDataURL("image/png");
</script>
create a form in ur body with a report button and an hidden field for URL :
<body>
<form action="pdfGen.php" id="download" method="post">
<iput type="hidden" id="imageURL" name="imageURL"/>
<input type="submit" value="Report" name="submit"/>
</form>
</body>
In your php page - pdfGen.php
<?php
$imageURL = $_REQUEST['imageURL'];
?>
Hope it helps.
EDIT
<script>
//<![CDATA[
(function() {
window.onload = function(){
html2canvas(document.getElementById('chart'), {
"onrendered": function(canvas) {
var img = new Image();
img.onload = function() {
img.onload = null;
console.log(canvas.toDataURL("image/png"));
document.getElementById('imageURL').value=this.src;
};
img.onerror = function() {
img.onerror = null;
if(window.console.log) {
window.console.log("Not loaded image from canvas.toDataURL");
} else {
//alert("Not loaded image from canvas.toDataURL");
}
};
img.src = canvas.toDataURL("image/png");
}
});
};
})();
//]]>
</script>

You can also creaate file from base64 and send it to server, like in this post (works from ie10 and all modern browsers)

Related

how to create an image file on server from dataurl

I have an image in a dataurl format, like:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwME…iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/2Q==
I need to convert this string in JavaScript to another string which can be directly copied to a blank jpg file so that it can be viewed by the user.
Any idea how to achieve this?
You just need to remove "data:image/jpeg;base64," from DataURI.
$dataUri = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgM...";
// remove "data:image/jpeg;base64," from image Data URI.
$data = str_replace("data:image/jpeg;base64,", "", $dataUri);
// save to file
file_put_contents("/tmp/image.jpeg", base64_decode($data));
If you want the user to be be able to download the file and save it somewhere on their computer, try this:
document.location.href = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQAB…";
See Download data url file if this is what you're trying to do.
To display it you can use the src attribute:
<img src="data:image/png;base64,R0lGODlhUAAPAKIAAA+g4JADs=" width="80" height="80" />
To generate a file you need use canvas element:
Example:
<html>
<head></head>
<body>
<canvas id="c"></canvas>
<script type="text/javascript" src="canvas2image.js"></script>
<script type="text/javascript" src="baseg4.js"></script>
<script type="text/javascript">
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
var image = new Image();
image.src = "data:image/png;base64,iVBORw0KG............5CYII%3D";
image.onload = function()
{
ctx.drawImage(image, 0, 0);
var foo = Canvas2Image.saveAsPNG(canvas);
};
var img = canvas.toDataURL("image/png");
</script>
</body>
</html>
And save the image and stuff... you can find a way to convert the canvas to a file in this link:
// http://www.nihilogic.dk/labs/canvas2image/
EDIT: New link, I guess...
https://github.com/hongru/canvas2image
You have to remove data:image/jpeg;base64, from the dataURI and decode the dataURI:
public void saveImage(String imageURI) {
BufferedImage image = null;
String blobString=imageString.replace("data:image/jpeg;base64,", "");
byte[] byteArray = Base64.getDecoder().decode(blobString);
ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);
try {
image = ImageIO.read(bis);
File file = new File("/home/rakesh/Vinay/a.jpeg");
ImageIO.write(image, "jpeg", file);
} catch (IOException e) {
e.printStackTrace();
}
}

read in a file from url or filesystem to variable in javascript

I am trying to read in a file from a file on my computer and store in in a variable.
I am currently trying:
var fr = new FileReader;
fr.onload = function() {
//variable to hold file
var data = fr.result;
var c=document.getElementById("cvs");
var ctx=c.getContext("2d");
ctx.drawImage(img,0,0,200,180);
};
fr.readAsDataURL("encryptedImage");
this does not work. I need to do this do i can decrypt an encrypted image on my file system. I have already turned of the security so my file system can be read from a browser.
any ideas?
From here it looks like you want to load the local file by passing a String to readAsArrayBuffer(), but it exspects a blob or file object. The file can be loaded via the browsers file dialog.
Steps are : Select the file, load the file via fileReader asArrayBuffer or asDataURL or asBinaryString ... and manipulate or use the data in your code.
For this example it creates an Image from the local file and draws it onto the canvas (if it's of correct mime type "image.*" however).
I'm not sure what kind of encoding/decoding you want to apply. But for custom manipulation of data I would recommend using ArrayBuffers and TypeArrays.
The example with FileReader.readAsDataURL(): http://jsfiddle.net/uvmD7/
<body>
<canvas id="cvs" width="200" height="200"></canvas>
<input type="file" id="files" name="files[]" multiple />
</body>
And the script:
document.getElementById('files').addEventListener('change', handleFileSelect, false);
var fr = new FileReader();
function handleFileSelect(evt) {
var files = evt.target.files;
fr.readAsDataURL(files[0]);
};
fr.onload = function(evt) {
// do sth with it
var data = evt.target.result; //fr.result
img = new Image();
img.src = data;
// draw after load
img.onload = function() {
var c=document.getElementById("cvs");
var ctx=c.getContext("2d");
ctx.drawImage(img,0,0,200,180);
};
};

Upload image using javascript

I'm trying to get image as Object of javascript on the client side to send it using jQuery
<html>
<body>
<script language="JavaScript">
function checkSize()
{
im = new Image();
im.src = document.Upload.submitfile.value;
if(!im.src)
im.src = document.getElementById('submitfile').value;
alert(im.src);
alert(im.width);
alert(im.height);
alert(im.fileSize);
}
</script>
<form name="Upload" action="#" enctype="multipart/form-data" method="post">
<p>Filename: <input type="file" name="submitfile" id="submitfile" />
<input type="button" value="Send" onClick="checkSize();" />
</form>
</body>
</html>
But in this code only alert(im.src) is displaying src of file but alert(im.width),alert(im.height),alert(im.filesize) are not working properly and alerting 0, 0, undefined respectively. Kindly tell me how I can access image object using javascript?
The reason that im.fileSize is only working in IE is because ".fileSize" is only an IE property. Since you have code that works in IE, I would do a check for the browser and render your current code for IE and try something like this for other browsers.
var imgFile = document.getElementById('submitfile');
if (imgFile.files && imgFile.files[0]) {
var width;
var height;
var fileSize;
var reader = new FileReader();
reader.onload = function(event) {
var dataUri = event.target.result,
img = document.createElement("img");
img.src = dataUri;
width = img.width;
height = img.height;
fileSize = imgFile.files[0].size;
alert(width);
alert(height);
alert(fileSize);
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsDataURL(imgFile.files[0]);
}
I haven't tested this code but it should work as long as I don't have some typo. For a better understanding of what I am doing here check out this link.
This is what I use and it works great for me. I save the image as a blob in mysql. When clicked, the file upload dialog appears, that is why i set the file input visibility to hidden and set its type to upload image files. Once the image is selected, it replaces the existing one, then I use the jquery post method to update the image in the database.
<div>
<div><img id="logo" class="img-polaroid" alt="Logo" src="' . $row['logo'] . '" title="Click to change the logo" width="128">
<input style="visibility:hidden;" id="logoupload" type="file" accept="image/* ">
</div>
$('img#logo').click(function(){
$('#logoupload').trigger('click');
$('#logoupload').change(function(e){
var reader = new FileReader(),
files = e.dataTransfer ? e.dataTransfer.files : e.target.files,
i = 0;
reader.onload = onFileLoad;
while (files[i]) reader.readAsDataURL(files[i++]);
});
function onFileLoad(e) {
var data = e.target.result;
$('img#logo').attr("src",data);
//Upload the image to the database
//Save data on keydown
$.post('test.php',{data:$('img#logo').attr("src")},function(){
});
}
});
$('#imagess').change(function(){
var total_images=$('#total_images').val();
var candidateimage=document.getElementById('imagess').value;
formdata = false;
var demo=document.getElementById("imagess").files;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = demo.length, img, reader, file;
for ( ; i < len; i++ ) {
file = demo[i];
if (file.type.match(/image.*/)) {
if (formdata) {
formdata.append("images", file);
}
}
}
$('#preview').html('Uploading...');
var url=SITEURL+"users/image_upload/"+total_images;
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
$('#preview').html('');
if (res == "maxlimit") {
alert("You can't upload more than 4 images");
}
else if (res == "error") {
alert("Image can't upload please try again.")
}
else {
$('#user_images').append(res);
}
}
});
});

Javascript: Verify External Url Of An Image

Suppose i have EXTERNAL URL(not from my website) and i want to verify it to make sure this url is one from these files:- jpg, jpeg, gif, png and also is a correct image file (not any script file or php). Also if this is possible:- Check if the url of the image is working or not.
#jfriend00 ok so here is what i'am trying to do. I had maded html form and when people submit it, it will call to a javascript function which will verify if the url is an image. So here is my code. But it's not working. Please tell me what should i do from here?
<script type="text/javascript">
function vrfyImgURL() {
var x = document.forms["submitIMGurl"].elements["img_url"].value;
if(x.match('^http://.*/(.*?).(jpe?g|gif|png)$')){
var imgsrc = x;
var img = new Image();
img.onerror = function(){
alert("Can't Be Loaded");
return false;
}
img.onload = function(){
alert("Loaded Successfully");
return true;
}
img.src = imgsrc;
}else{
alert("It looks like the url that you had provided is not valid! Please only submit correct image file. We only support these extensions:- jpeg, jpg, gif, png.");
return false;
}
}
</script>
<form action="http://www.example.com/current_page" enctype='multipart/form-data' method="post" onsubmit="return vrfyImgURL();" name="submitIMGurl">
<input type="text" value="http://" name="img_url" />
<input type="submit" value="Submit" />
</form>
Your code in this post is not a correct implementation of the function I gave you in the previous post and will not work for a number of reasons. You cannot return true/false from the onload, onerror handlers. Those are asychronous events and your vrfyImgURL function has already returned.
You really HAVE to use the code I put in that previous post. It works. Just use it. Don't modify it. You pass in a callback and that callback gets called with the validation check results. You have to use asynchronous programming to use this where the callback gets called with the result. You can't use straight sequential programming like you are trying to do. It is your modifications to my code that have made it stop working.
You can see the code I gave you previously work here:http://jsfiddle.net/jfriend00/qKtra/ and in the example, it's working with images from a variety of domains. It is not sensitive to the domain of the image and <img> tags are not restricted by domain.
To hook it up to your form submit, you can do this:
<form action="http://www.example.com/current_page" enctype='multipart/form-data' method="post" onsubmit="return formSubmit();" name="submitIMGurl">
<input type="text" value="http://" name="img_url" />
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
function formSubmit() {
var url = document.forms["submitIMGurl"].elements["img_url"].value;
if (!checkURL(url)) {
alert("It looks like the url that you had provided is not valid! Please only submit correct image file. We only support these extensions:- jpeg, jpg, gif, png.");
return(false);
}
testImage(url, function(testURL, result) {
if (result == "success") {
// you can submit the form now
document.forms["submitIMGurl"].submit();
} else if (result == "error") {
alert("The image URL does not point to an image or the correct type of image.");
} else {
alert("The image URL was not reachable. Check that the URL is correct.");
}
});
return(false); // can't submit the form yet, it will get sumbitted in the callback
}
function checkURL(url) {
return(url.match(/\.(jpeg|jpg|gif|png)$/) != null);
}
function testImage(url, callback, timeout) {
timeout = timeout || 5000;
var timedOut = false, timer;
var img = new Image();
img.onerror = img.onabort = function() {
if (!timedOut) {
clearTimeout(timer);
callback(url, "error");
}
};
img.onload = function() {
if (!timedOut) {
clearTimeout(timer);
callback(url, "success");
}
};
img.src = url;
timer = setTimeout(function() {
timedOut = true;
callback(url, "timeout");
}, timeout);
}
</script>
If this were my interface, I would disable the form and put up a note that the image URL is being checked starting when testImage is called and ending when the callback is called.

downloading a javascript blob variable as mhtml

I'm writing a google chrome extension that uses
chrome.pageCapture.saveAsMHTML(object details, function callback)
function callback (blob mhtmlData) {...};
http://code.google.com/chrome/extensions/dev/pageCapture.html
which basically stores a blob representation of an mhtml page into a variable.
Now I want to let the user download this blob variable as an mhtml file..
I tried this but is gives me a 200kb file filled with random characters.
chrome.pageCapture.saveAsMHTML({tabId: sender.tab.id}, function callback(mhtml){
var reader = new FileReader();
reader.readAsDataURL(mhtml);
reader.onload = function(e) {
window.open(e.target.result);
}
});
Following is some code that I put in a page actions popup. I left the stuff that I didnt use but commented it out for reference.
EDIT:
Using the library from https://github.com/eligrey/FileSaver.js it was easy, maybe you could look at that to see what their doing.
popup.html
<html>
<head>
<script xmlns="http://www.w3.org/1999/xhtml" type="application/ecmascript" async="" src="https://raw.github.com/eligrey/FileSaver.js/master/FileSaver.min.js"></script>
<script>
function onLoad(){
var downloadLink = document.querySelector("#MHTML");
var oFReader = new FileReader();
oFReader.onload = function (oFREvent) {
// None of the following worked
//window.open('data:application/octet-stream;'+oFREvent.target.result.slice(5));
//window.open('data:application/message/rfc822;'+oFREvent.target.result.slice(5));
//window.open(oFREvent.target.result);
};
chrome.tabs.getSelected(null, function(tab) {
chrome.pageCapture.saveAsMHTML({tabId: tab.id}, function (mhtml){
/// Works but requires user input
//downloadLink.setAttribute('download',tab.title+'.mhtml');
//downloadLink.setAttribute('href',window.webkitURL.createObjectURL(mhtml));
///Works but awful filename without extension
//window.open(window.webkitURL.createObjectURL(mhtml));
///Doesnt work
//oFReader.readAsDataURL(mhtml);
///Using https://github.com/eligrey/FileSaver.js , works great
saveAs(mhtml, tab.title+'.mhtml');
})
});
}
</script>
</head>
<body onload="onLoad();" style="width: 400px">
<a id="MHTML" href="#">Download Page As MHTML</a>
</body>
</html>
In case you want to give the file a name you could use an anchor element and set the name of the download attribute programmatically:
var reader = new FileReader();
reader.readAsDataURL(mhtml);
reader.onloadend = function(e) {
const dataUrl = e.target.result;
const a = document.createElement('a');
a.href = dataUrl;
a.download = fileName;
a.click();
}

Categories

Resources