I have a page with a google map in it and some data in a couple of divs, I need the user to click "Grab Screenshot" button and that should save the screenshot of the user's page and save it to the server.
I tried through Html2Canvas, but it is not allowing me to convert canvas to dataurl i.e in my javascript function, I used this:
function GenerateImage()
{
html2canvas($('#mainDiv'), {
onrendered: function(canvas) {
//this appends the canvas(screenshot) to the page, this is working fine
document.body.appendChild(canvas);
//this is not working,
//Error: SecurityError: The operation is insecure.
var image = canvas.toDataURL('image/png');
image.crossOrigin = 'anonymous';
var imgdata = image.replace(/^data:image\/(png|jpg);base64,/, '');
$.ajax({
url: '******',
data: {
imgdata:imgdata
},
type: 'post',
success: function (response) {
console.log('Success');
}
});
}
});
}
I did research, I found out it is some CORS issue, but I am unable to figure out a solution.
So, I was wondering if I can do a screenshot using ASP.net, is that possible? Thanks in advance.
I was able to successfully do it using the proxy. I had an issue with a custom marker icon from a different website on the map. That was causing the canvas to taint. I moved the image to my website and changed the path, the "tainted canvases may not be exported" error went away.
Related
I am trying to save images for an Application to the localFolder with the help of the Winjs.xhr function. This works totally fine, but if I want to put the picture to the src attribute of an image I always get Error DOM7009: Unable to decode image at URL ms-appdata:///local/name.png. I tried it with different images but this error always occures.
Javascript:
var imgUrl = "http://www.microsoft.com/windows/Framework/images/win_logo.png";
WinJS.xhr({
url: imgUrl,
responseType: "blob"
}).then(
function completed(result) {
var newFile = result.response;
var localFolder = Windows.Storage.ApplicationData.current.localFolder;
var fileName = "image.png";
var CreationCollisionOption = Windows.Storage.CreationCollisionOption;
return localFolder.createFileAsync(fileName,CreationCollisionOption.replaceExisting);
}).then(
function createFileSuccess() {
var msgtext = "File downloaded successfully!";
var msg = new Windows.UI.Popups.MessageDialog(msgtext);
return msg.showAsync();
});
HTML:
<img src="ms-appdata:///local/image.png"/>
What am I doing wrong?
Edit: I saw other people also having "the unable to decode" error on Internet Explorer. There the problem seemed to be using very large images. But im only working with icon-sized images, so it seems to be a different problem.
solved at https://social.msdn.microsoft.com/Forums/windowsapps/en-US/6352bce1-1427-47ec-9dab-dc41cda165c4/winjswinjs-dom7009-unable-to-decode-image-at-url?forum=wpdevelop#6352bce1-1427-47ec-9dab-dc41cda165c4
I opened the file, but wrote nothing in it.
I currently have a script that successfully creates an image from canvas including its containing Div background image by using html2canvas. I also have a script that can save the canvas as an image to the server using the canvas2image plugin but the background doesn't show up.
The problem I'm having is when I try to combine the two so that I can save the Div bg and canvas as an image to the server, nothing happens which I believe is due to the canvas2image plugin not firing.
The code I have with both plugins combined is here.
function exportAndSaveCanvas() {
html2canvas($("#containingDiv"), {
background:'#fff',
onrendered: function(canvas) {
// var imgData = canvas.toDataURL('image/jpeg'); <--This would create the image needed
//but I replaced with the line below to tie in the two plugins
var screenshot = Canvas2Image.saveAsPNG(canvas, true);
canvas.parentNode.appendChild(screenshot);
screenshot.id = "canvasimage";
data = $('#canvasimage').attr('src');
canvas.parentNode.removeChild(screenshot);
// Send the screenshot to PHP to save it on the server
var url = 'upload/export.php';
$.ajax({
type: "POST",
url: url,
dataType: 'text',
data: {
base64data : data
}
});
}
});
}
The code for export.php which upload the image to the server is here
<?php
$data = $_REQUEST['base64data'];
//echo $data;
$image = explode('base64,',$data);
file_put_contents('../uploadimg/myImage.jpg', base64_decode($image[1]));
?>
I was hoping to be able to combine the two plugins to work together and get my canvas with Div background save to the server but it looks like the canvas2image plugin doesn't fire.
Thanks!
Write the background image into the canvas before you write the other image. The MDN page about writing an image to a canvas should have you covered: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images
As an aside, I'm not sure why you're using a plugin to do anything you get for free with the native canvas API.
dtanders said "As an aside, I'm not sure why you're using a plugin to do anything you get for free with the native canvas API."
This got me thinking that I was making it more difficult than it needed to be so I stripped away some code. The script below does just what I need.
function exportAndSaveCanvas() {
html2canvas($("#containingDiv"), {
background:'#fff',
onrendered: function(canvas) {
var imgData = canvas.toDataURL('image/jpeg');
var url = 'upload/export.php';
$.ajax({
type: "POST",
url: url,
dataType: 'text',
data: {
base64data : imgData
}
});
}
}); //End html2canvas
} // End exportAndSaveCanvas()
I am making a phonegap app, in which the user submits a photo from his camera, i get it in a Base64 encoding form.
var posData=extImage1;
$.ajax({
type: 'POST',
data: posData,
timeout:50000,
url: 'http://192.168.137.1/bee/services/add_photo.php',
success: function(data){
alert(data);
addToList();
},
error: function(){
alert('Please check your internet connection');
}
});
server side the code is saved to the database, but when selected and used as div background; it won't work no matter what!
BG='url(' + "data:image/jpeg;base64," + item.car_intImage3+ ')';
$('#item').css('background',BG);
why this is happening ? my guess is that during posting the data it got scrambled somehow.
I tried to save the image on server using the code from this question, but it just gives a corrupted image.
Update:
Using this decoder i submitted the posted 64 code and it also gives corrupted image. i think that means that there is something wrong with my post method. any suggestions?
It would be a lot cleaner and easier if you use Dropzone.js
Take a look at Dropzone.js Implementation. It is quite easy
This is how you can instantiate it
var myDropzone = new Dropzone("div#myId", { url: "/file/post"});
You can also listen to a lot of events like Adding a file, Removing a file
For Ex:
Dropzone.options.myAwesomeDropzone = {
init: function() {
this.on("addedfile", function(file) { alert("Added file."); });
}
};
EDIT: The Above solutions will work if you are storing the image in your disk and just the image location in your database. In fact it would be a lot better if you do this way.
Now coming to your method of working with images, You would want to go through this link how-can-i-store-and-retrieve-images-from-a-mysql-database-using-php which has a straight forward answer
Also, Check the datatype that you are using, may be its truncating he encoded data that you are storing in the database and hence you might be getting corrupted images. Also check with the above method of storing the images in the database mentioned in the link.
Hope this solves your problem
I created a coupon-creator system that uses HTML 5 canvas to spit out a jpg version of the coupon you create and since I'm not hosting the finalized jpg on a server, I am having trouble retrieving the URL. On some browsers when I drag the image into the address bar all I get is "data:" in the address bar. But on windows, if I drag it into an input field, sometimes it spits out the huge (>200 char) local-temp url. How can I use javascript(?) to find that exact temporary URL of the image generated by my coupon creator and be able to post it on an input form on the same page? Also, it'd be very helpful if you guys know the answer to this as well, as I assume it is correlated with the retrieval of the URL: When I click the link that says "Save it" after it's generated, how can I have it save the created image to the user's computer? Thanks a lot!
This is what I'm using in JS right now to generate the image:
function letsDo() {
html2canvas([document.getElementById('coupon')], {
onrendered: function (canvas) {
document.getElementById('canvas').appendChild(canvas);
var data = canvas.toDataURL('image/jpeg');
// 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 mycustomcoupon = new Image();
mycustomcoupon.src = data;
//Display the final product under this ID
document.getElementById('your_coupon').appendChild(mycustomcoupon);
document.getElementById('your_coupon_txt').style.display="block";
}
});
}
Here is the live URL of the creator: http://isleybear.com/coupon/
I ended up dumping this code into the js stated above. It was a pretty simple fix. Then to test it, I set an onclick html element to show the source.
var mycustomcoupon = document.getElementById('your_coupon');
mycustomcoupon.src = data;
}
});
}
function showSource(){
var source = document.getElementById('your_coupon').src;
alert(source);
}
I have a form where users can paste the external url of an image. Is it possible via javascript to go and grab that file and then POST it to a REST API? I'm using parse.com for the rest api.
… external url of an image. Is it possible via javascript to go and grab that file …
No. This is prevented by the same origin policy, you will not be allowed to access it. Just post the URL of it to your REST api and fetch it on the server side.
While you cannot access the file or data associated with it, of course you can display it by embedding via an <img> element.
One way or another, the image will first have to be pulled onto your server due to restrictions on working with cross-origin resources. Once you have done this you can use my elaborate example to convert the image into Base64 and then into a JSON string ready to be transported via POST to your REST server:
<input id="urlText" />
<input id="sendData" type="submit" />
<img id="img" src="http://fiddle.jshell.net/img/logo.png" />
<script>
var imgElem = document.getElementById('img');
$('#urlText').keyup(function(){
$('#img').attr('src',$('#urlText').val());
});
$('#sendData').click(function(){
var imgData = JSON.stringify(getBase64Image(imgElem));
$.ajax({
url: 'http://url.com/rest/api',
dataType: 'json',
data: imgData,
type: 'POST',
success: function(data) {
console.log(data);
}
});
});
function getBase64Image(imgElem) {
// imgElem must be on the same server otherwise a cross-origin error will be thrown "SECURITY_ERR: DOM Exception 18"
var canvas = document.createElement("canvas");
canvas.width = imgElem.clientWidth;
canvas.height = imgElem.clientHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(imgElem, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
</script>
My jsFiddle example is here.