HTML5 Canvas Drag out from browser to desktop - javascript

I'm trying to create a little image manipulation web app as a project. I'm trying to implement a Drag canvas image out of the browser to the desktop. I have done some digging and found
http://www.thecssninja.com/javascript/gmail-dragout and http://jsfiddle.net/bgrins/xgdSC/ (courtesy of TheCssNinja & Brian Grinstead)
function dragoutImages() {
if (!document.addEventListener) {
return;
}
document.addEventListener("dragstart", function(e) {
var element = e.target;
var src;
if (element.tagName === "IMG" && element.src.indexOf("data:") === 0) {
src = element.src;
}
if (element.tagName === "CANVAS") {
try {
src = element.toDataURL();
}
catch(e) { }
}
if (src) {
var name = element.getAttribute("alt") || "download";
var mime = src.split(";")[0].split("data:")[1];
var ext = mime.split("/")[1] || "png";
var download = mime + ":" + name + "." + ext + ":" + src;
e.dataTransfer.setData("DownloadURL", download);
}
}, false);
}
function drawCanvas(){
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
var lingrad = ctx.createLinearGradient(0,0,0,150);
lingrad.addColorStop(0, '#000');
lingrad.addColorStop(0.5, '#669');
lingrad.addColorStop(1, '#fff');
ctx.fillStyle = lingrad;
ctx.fillRect(0, 0, canvas.width, canvas.height);
var img = new Image();
img.src = canvas.toDataURL("image/png");
img.alt = 'downloaded-from-image';
$(img).appendTo("body");
}
dragoutImages();
drawCanvas();
This works for files which are elements of the HTML but I am unable to grab the canvas image and download it using the theory. Has anyone implemented such a feature?
I have used the canvas.toDataURL to get the image data, if I do an alert I see the encoded image data my canvas drag begins but when outside the browser the icon changes back to the stop symbol.
Looking for approaches and ideas on how to implement this.
This is what I've managed to implement and works pretty well,
function download(e){
downloadImageData = eCanv.getImageData(750 - (scaledWidth / 2), 250 - (scaledHeight / 2), scaledWidth, scaledHeight);
dlcanvas = document.createElement('canvas');
dlcanvas.setAttribute('width',scaledWidth);
dlcanvas.setAttribute('height',scaledHeight);
dlcontext = dlcanvas.getContext("2d");
dlcontext.putImageData(downloadImageData, 0,0);
url = dlcanvas.toDataURL('image/jpg');
//name = document.getElementById("filename").value;
var mime = url.split(";")[0].split("data:")[1];
var name = mime.split("/")[0];
var ext = mime.split("/")[1] || "jpg";
var download = mime + ":" + name + "." + ext + ":" + url;
e.dataTransfer.setData("DownloadURL", download);
}
Adapted code from cssninja and Brian Grinstead.

No.
For security reasons, Javascript cannot write to the local file system.
Javascript can read from the local file system with the filereader: http://www.html5rocks.com/en/tutorials/file/dndfiles/
It can even write to a sandboxed browser file (localstorage): http://www.w3schools.com/html/html5_webstorage.asp
You could even bounce it off your server and then ask the user if they want to download the image off the server.

For local web based applications you can use or write a local webserver or service and or utilzize for example php to add the functionality to interact with the local filesystem from javascript. Seems this is forgotten that it is not forbidden to install a webserver on the same machine like the browser :)

Related

jsPDF - Getting black images on IE, but works fine on Chrome and FireFox

I need some help with the following problem, when I get a pdf with images on Chrome and FireFox I can get a good résult, jsPDF put on it some blur but I can live with it.
Result on Chrome
In other hand, on IE 10,11 and Edge the result is the following:
Result on IE
If you notice we can see something on pictures but almost is black.
Those are charts from highcharts and I convert svg to canvas.
I put some snippets but I can send to email the whole example:
var doc = new jsPDF('p', 'pt', 'a4', true);
var centered_x = (doc.internal.pageSize.width / 2) - ((context.destWidth / 2) * 0.75);
imgData_1 = atob(imgData_1);
doc.addImage(imgData_1, 'png', centered_x, 50);
data.datauri = context.browserSupportDownload && doc.output('datauristring');
data.blob = context.browserSupportBlob && doc.output('blob');
I call the function download to send the stream to the browser and its definition is like that:
var download = function(highChartsObject, context, data) {
if (!data || (!data.content && !(data.datauri || data.blob))) {
throw new Error("Something went wrong while exporting the chart");
}
if (context.browserSupportDownload && (data.datauri || data.content)) {
a = document.createElement('a');
a.href = data.datauri || ('data:' + context.type + ';base64,' + window.btoa(unescape(encodeURIComponent(data.content))));
a.download = 'result_good.pdf';
document.body.appendChild(a);
a.click();
a.remove();
}
else if (context.browserSupportBlob && (data.blob || data.content)) {
blobObject = data.blob || new Blob([data.content], { type: context.type });
window.navigator.msSaveOrOpenBlob(blobObject, 'IE_CASE.pdf');
}
else {
//window.open(data);
window.navigator.msSaveOrOpenBlob(blobObject, 'IE_CASE.pdf');
}
};
Thanks in advance.
Try changing the background color of the image using canvas or svg.
https://github.com/MrRio/jsPDF/issues/247

How to download an image object from webgl/javascript

I have a directory with 100 images. I need a copy of them in various folders along with other information that I download from webgl. Hence I want to upload them onto the browser and download them again (hope that isn't stupid)
Here is my code:
var imagefile = model.features[cIndex].imageName.substring(model.features[cIndex].imageName.lastIndexOf('/')+1);
var image = new Image();
image.src = model.imageDirectory + imagefile;
image.onload = function() {
console.info("Read \""+image.src + "\"...Done");
}
image.onerror = function() {
var message = "Unable to open \"" + image.src + "\".";
console.error(message);
alert(message);
}
var data = image.src;
zip.file('image_RH_Original' + cIndex +'.png', data , {base64: true});
Is this wrong? How to I do something similar to "toDataURL" for the image object?
toDataURL is a method of canvas, and webgl draws to a canvas. So just call canvas.toDataURL(). Probably need to set preserveDrawingBuffer to true as well.

Upload Picture as base64 String to Parse

I have following Problem.
I´m using a canvas to resize pictures a user uploaded to my webapp.
Then I retrieve the picture from the canvas as a base64 encoded string and try to upload it to the parse server.
Since parse supports base64 I thought it could work.
When i upload the images however, there is no image but instead this message for every image file i upload:
{"_ContentType":"image/jpg","_ApplicationId":"MY APPLICATION
ID","_JavaScriptKey":"MY JAVASCRIPT
KEY","_ClientVersion":"js1.3.5","_InstallationId":"THE INSTALLATION
ID","_SessionToken":"THE SESSION TOKEN OF THE CURRENT USER"}
I can retrieve the files, but what i get is no image.
Here is my code for uploading the pictures:
var fileUploadControl = $("#product_pictureUploadModal")[0];
if (fileUploadControl.files.length > 0) {
//THE USER SUCCESSFULLY SELECTED A FILE
var file = fileUploadControl.files[0];
if(file.type.match(/image.*/)){
//RESIZE THE IMAGE AND RETURN a base64 STRING
var resizedImage = resizeImage(file);
//CREATE A PARSE FILE
var name = "picture.jpg";
var parseFile = new Parse.File(name, {base64: resizedImage}, "image/jpg");
parseFile.save().then(function() {
//IMAGE SUCCESSFULLY UPLOADED
},
function(error){
alert(error.message);
});
}else{
//THE USER DIDNT CHOSE A PICTURE
}
}else{
//THE USER DIDNT SELECT A FILE
}
Here is my code for resizing the pictures:
function resizeImage(file){
var MAX_WIDTH = 400;
var image = new Image();
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var url = window.URL || window.webkitURL;
var src = url.createObjectURL(file);
image.src = src;
return image.onload = function(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
if(image.width > MAX_WIDTH){
if(image.width > image.height){
image.height = (image.height%image.width)*400;
}else{
image.height = (image.height/image.width)*400;
}
alert("image height " + image.height);
image.width = 400;
}
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0, image.width, image.height);
url.revokeObjectURL(src);
var fileRezized = encodeURIComponent(canvas.toDataURL("image/jpg"));
return fileRezized;
};
}
What am i missing here?
I hope you guys could help me. I put a lot of work and time in this already and I seem to not get any further than this.
I want to resize the image in the browser because otherwise upload speed might be too slow for some people, as my application will be available for mobile phones as well.
greetins from germany, marvin
When you get no dataURL back from the browser, it's often caused by a cross-domain security violation.
The users image likely does not originate on the same domain as your web page, so when you drawImage the users image to the canvas, you are "tainting" the canvas. This tainting will cause .toDataURL to be disallowed which will in turn cause the DataURL uploaded to your server to be empty.
One workaround
As a workaround, you can "round-trip" the user's image:
upload the users image to your server and save it in the same domain as your web pages.
reload the users browser page along with their image served from your own domain.
Another workaround: FileReader
If your users have modern browsers that support FileReader then you can let your users upload images from their local drives in a security compliant way.
Here's example code using FileReader:
function handleFiles(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var img = document.createElement("img");
img.classList.add("obj");
img.file = file;
var reader=new FileReader();
reader.onload=(function(aImg){
return function(e) {
aImg.onload=function(){
var canvas=document.createElement("canvas");
var ctx=canvas.getContext("2d");
canvas.width=aImg.width;
canvas.height=aImg.height;
ctx.drawImage(aImg,0,0);
document.body.appendChild(document.createElement('br'));
document.body.appendChild(canvas);
var u=canvas.toDataURL();
var textarea=document.createElement('textarea');
textarea.value=u;
document.body.appendChild(textarea);
}
// e.target.result is a dataURL for the image
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
} // end for
} // end handleFiles
//
$("#fileElem").change(function(e){ handleFiles(this.files); });
body{ background-color: ivory; }
canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Example: load images to canvas while satisfying security requirements.</h4>
<input type="file" id="fileElem" multiple accept="image/*">
<br>
There is an error in this line:
var fileRezized = encodeURIComponent(canvas.toDataURL("image/jpg"));
There is no mime-type image/jpg in canvas. This would actually default to image/png instead which I guess could confuse the receiver. Just correct the line to:
var fileRezized = encodeURIComponent(canvas.toDataURL("image/jpeg"));
I don't know parse.com, but also try doing this with this line:
var parseFile = new Parse.File(name, {base64: resizedImage}, "image/jpeg");
// ^^
Test case
var canvas = document.querySelector("canvas"), out = document.querySelector("div");
out.innerHTML = canvas.toDataURL("image/jpg") + "<br><br>"; // PNG
out.innerHTML += canvas.toDataURL("image/jpeg"); // JPEG
<canvas width=1 height=1></canvas><div></div>

Convert Svg to Png on Client Side

I am working on a Web based application where user can create designs in Svg. i want to convert the svg design into png image file on client side. i found a solution of using canvas, this works well in firefox, but in chrome it generate security error.
check the code below thanks:-
var mainsvg=document.getElementById('svgforImg');
var canvas=document.getElementById('canvas');
var ctx = canvas.getContext("2d");
var data=mainsvg.innerHTML;
var DOMURL = self.URL || self.webkitURL || self;
var svg = new Blob([data], {
type: "image/svg+xml;charset=utf-8"
});
var url = DOMURL.createObjectURL(svg);
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
var imageurl = canvas.toDataURL("image/png");
}
Now my variable imageurl contains 'base64 png' image. this works in Firefox. But in chrome line
var imageurl = canvas.toDataURL("image/png");
generate security error.
Any help would be highly appreciated.
I think this is related to this question. From which server does the SVG originate? If it is a different one than the one your application is coming from (remember: sub-domains matter!), you could add the desired http-headers in the originating server.

canvas.toDataURL() not working properly except mozilla firefox

I have developed a coupon generator module in the site I create a coupon in the html format and fill that html value in canvas by using JavaScript function which is
function checkcanvas(id) {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var data = "<svg xmlns='http://www.w3.org/2000/svg' width='437' height='262'>"
+ "<foreignObject width='100%' height='100%'>"
+ "<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:40px'>"
+ $("#coupon_td").html()
+ "</div>"
+ "</foreignObject>"
+ "</svg>";
var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
var svg = new Blob([data], {type: "image/svg+xml;charset=utf-8"});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
};
img.src = url;
if(id == 2) {
document.getElementById('base_64_img').value = canvas.toDataURL();
}
}
base_64_img is just a hidden element so I can post the data into my php code and create a image using base64 code.
The biggest issue I am facing that this code perfectly worked in Mozilla Firefox almost every version but not working in Google chrome.
In your code you are generating an "SVG IMAGE" and trying to convert into toDataURL().
var svg = new Blob([data], {type: "image/svg+xml;charset=utf-8"});
This is the problem, from this URL toDataURL :
If the type requested is not image/png, and the returned value starts
with data:image/png, then the requested type is not supported.
In this fiddlecode if you see the printed output , "data:image/png;base64". its supposed to be "data:image/svg;base64".
Instead of creating svg image, use canvas element and javascript to draw the related banner image and if you take the output then try copy & paste in your browser. ( it may work ).
Check this js plugin called SVG.toDataURL
Hope this helps.

Categories