I have a requirement where I need to store the GIF image in local storage. I have been trying to do this using following code:
function imgToURI(image) {
var canvasTemp = document.createElement('canvas');
canvasTemp.width = image.naturalWidth; // or 'width' if you want a special/scaled size
canvasTemp.height = image.naturalHeight; // or 'height' if you want a special/scaled size
canvasTemp.getContext('2d').drawImage(image, 0, 0);
var dataUri = canvasTemp.toDataURL('image/gif');
// Modify Data URI beginning
dataUri = 'data:image/gif;' + dataUri.substring(15);
return dataUri;
}
window.onload = function () {
var img = new Image();
img.src = 'http://pop.h-cdn.co/assets/16/33/480x264/gallery-1471381857-gif-season-2.gif';
localStorage.setItem('test', imgToURI(img));
};
The above code outputs data:image/gif; in local storage. Also I can't find any errors on console.
I have been trying a lot but don't know why image is not getting stored. Please let me know if you have solution to above problem.
maybe when your code is executed the image was not loaded yet. So only the string 'data:image/gif will be saved
var img = new Image();
img.addEventListener('load', function() {
localStorage.setItem('test', imgToURI(img));
}, false);
img.src = 'http://pop.h-cdn.co/assets/16/33/480x264/gallery-1471381857-gif-season-2.gif';
this code will attempt to save the image only if its loaded completely
EDIT
You are having this error because the image the image is not coming from your server: this CORS issue. you can try this but you have to trust the server who host the image
just before the addEventListener
img.setAttribute('crossOrigin', 'anonymous');
It can be due to Cross-Origin request not allowing you to get the canvas data. You have to make sure to use an image from a "trusted" source (server which allows Cross-Origin on your domain), so that your canvas doesn't get tainted.
Related
So I'm using google maps and I get the picture so it looks like this
<img id="staticMap"
src="http://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=600x300&maptype=roadmap
&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318
&markers=color:red%7Ccolor:red%7Clabel:C%7C40.718217,-73.998284&sensor=false">
I need to save it. I have found this:
function getBase64FromImageUrl(URL) {
var img = new Image();
img.src = URL;
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL("image/png");
alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));
};
}
But I get this problem:
Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': tainted canvases may not be exported.
I searched for fixes. I found a sample here How to use CORS but still I can't tie these 2 pieces of code together to make it work. Maybe I'm doing it the wrong way and there is a simpler way to do it? I'm trying to save this pic so that I can transfer the data to my server. So maybe someone did something like this and knows how to make .toDataURL() work as I need it?
Unless google serves this image with the correct Access-Control-Allow-Origin header, then you wont be able to use their image in canvas. This is due to not having CORS approval. You can read more about this here, but it essentially means:
Although you can use images without CORS approval in your canvas,
doing so taints the canvas. Once a canvas has been tainted, you can no
longer pull data back out of the canvas. For example, you can no
longer use the canvas toBlob(), toDataURL(), or getImageData()
methods; doing so will throw a security error.
This protects users from having private data exposed by using images
to pull information from remote web sites without permission.
I suggest just passing the URL to your server-side language and using curl to download the image. Be careful to sanitise this though!
EDIT:
As this answer is still the accepted answer, you should check out #shadyshrif's answer, which is to use:
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
This will only work if you have the correct permissions, but will at least allow you to do what you want.
Just use the crossOrigin attribute and pass 'anonymous' as the second parameter
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
This method will prevent you from getting an 'Access-Control-Allow-Origin' error from the server you are accessing to.
var img = new Image();
var timestamp = new Date().getTime();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url + '?' + timestamp;
Try the code below ...
<img crossOrigin="anonymous"
id="imgpicture"
fall-back="images/penang realty,Apartment,house,condominium,terrace house,semi d,detached,
bungalow,high end luxury properties,landed properties,gated guarded house.png"
ng-src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
height="220"
width="200"
class="watermark">
In my case I was using the WebBrowser control (forcing IE 11) and I could not get past the error. Switching to CefSharp which uses Chrome solved it for me.
I had the same error message. I had the file in a simple .html, when I passed the file to php in Apache it worked
html2canvas(document.querySelector('#toPrint')).then(canvas => {
let pdf = new jsPDF('p', 'mm', 'a4');
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298);
pdf.save(filename);
});
if the picture from the 3rd party site didn't set the header for cors ("access-control-allow-origin"), you can never download the picture file through chrome,
even if you use the setAttribute('crossOrigin', 'anonymous');
Here are some suggestions
hack chrome (use an extension, this will only work on your machine)
proxy the image through a service running on your site. The browser will see the domain as your site. This requires your service to request the image from the 3rd party.
By using fabric js we can solve this security error issue in IE.
function getBase64FromImageUrl(URL) {
var canvas = new fabric.Canvas('c');
var img = new Image();
img.onload = function() {
var canvas1 = document.createElement("canvas");
canvas1.width = this.width;
canvas1.height = this.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL({format: "png"});
};
img.src = URL;
}
So I'm using google maps and I get the picture so it looks like this
<img id="staticMap"
src="http://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=600x300&maptype=roadmap
&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318
&markers=color:red%7Ccolor:red%7Clabel:C%7C40.718217,-73.998284&sensor=false">
I need to save it. I have found this:
function getBase64FromImageUrl(URL) {
var img = new Image();
img.src = URL;
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL("image/png");
alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));
};
}
But I get this problem:
Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': tainted canvases may not be exported.
I searched for fixes. I found a sample here How to use CORS but still I can't tie these 2 pieces of code together to make it work. Maybe I'm doing it the wrong way and there is a simpler way to do it? I'm trying to save this pic so that I can transfer the data to my server. So maybe someone did something like this and knows how to make .toDataURL() work as I need it?
Unless google serves this image with the correct Access-Control-Allow-Origin header, then you wont be able to use their image in canvas. This is due to not having CORS approval. You can read more about this here, but it essentially means:
Although you can use images without CORS approval in your canvas,
doing so taints the canvas. Once a canvas has been tainted, you can no
longer pull data back out of the canvas. For example, you can no
longer use the canvas toBlob(), toDataURL(), or getImageData()
methods; doing so will throw a security error.
This protects users from having private data exposed by using images
to pull information from remote web sites without permission.
I suggest just passing the URL to your server-side language and using curl to download the image. Be careful to sanitise this though!
EDIT:
As this answer is still the accepted answer, you should check out #shadyshrif's answer, which is to use:
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
This will only work if you have the correct permissions, but will at least allow you to do what you want.
Just use the crossOrigin attribute and pass 'anonymous' as the second parameter
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
This method will prevent you from getting an 'Access-Control-Allow-Origin' error from the server you are accessing to.
var img = new Image();
var timestamp = new Date().getTime();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url + '?' + timestamp;
Try the code below ...
<img crossOrigin="anonymous"
id="imgpicture"
fall-back="images/penang realty,Apartment,house,condominium,terrace house,semi d,detached,
bungalow,high end luxury properties,landed properties,gated guarded house.png"
ng-src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
height="220"
width="200"
class="watermark">
In my case I was using the WebBrowser control (forcing IE 11) and I could not get past the error. Switching to CefSharp which uses Chrome solved it for me.
I had the same error message. I had the file in a simple .html, when I passed the file to php in Apache it worked
html2canvas(document.querySelector('#toPrint')).then(canvas => {
let pdf = new jsPDF('p', 'mm', 'a4');
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298);
pdf.save(filename);
});
if the picture from the 3rd party site didn't set the header for cors ("access-control-allow-origin"), you can never download the picture file through chrome,
even if you use the setAttribute('crossOrigin', 'anonymous');
Here are some suggestions
hack chrome (use an extension, this will only work on your machine)
proxy the image through a service running on your site. The browser will see the domain as your site. This requires your service to request the image from the 3rd party.
By using fabric js we can solve this security error issue in IE.
function getBase64FromImageUrl(URL) {
var canvas = new fabric.Canvas('c');
var img = new Image();
img.onload = function() {
var canvas1 = document.createElement("canvas");
canvas1.width = this.width;
canvas1.height = this.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL({format: "png"});
};
img.src = URL;
}
I'm trying to base64 encode a local file. It's next to my .js file so there's no uploading going on. Solutions like this (using XMLHttpRequest) get a cross-site scripting error.
I'm trying something like this (which doesn't work but it might help explain my problem):
var file = 'file.jpg'
var reader = new FileReader();
reader.onload = function(e) {
var res = e.target.result;
console.log(res);
};
var f = reader.readAsDataURL(file);
Anyone have any experience doing this locally?
Solutions like this (using XMLHttpRequest) get a cross-site
scripting error.
If using chrome or chromium browser, you could launch with --allow-file-access-from-files flag set to allow request of resource from local filesystem using XMLHttpRequest() or canvas.toDataURL().
You can use <img> element, <canvas> element .toDataURL() to create data URL of local image file without using XMLHttpRequest()
var file = "file.jpg";
var img = new Image;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
img.onload = function() {
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
ctx.drawImage(this, 0, 0);
var res = canvas.toDataURL("image/jpeg", 1); // set image `type` to `image/jpeg`
console.log(res);
}
img.src = file;
You could alternatively use XMLHttpRequest() as described at Convert local image to base64 string in Javascript.
See also How to print all the txt files inside a folder using java script .
For a details of difference of returned data URI from either approach see canvas2d toDataURL() different output on different browser
As described by #Kaiido at comment below
it will first decode it, at this stage it's still your file, then it
will paint it to the canvas (now it's just raw pixels) and finally it
will reencode it (it has nothing to do with your original file
anymore) check the dataURI strings... They're compeltely different and
even if you do the canvas operation from two different browsers,
you'll have different outputs, while FileReader will always give you
the same output, since it encode the file directly, it doesn't decode
it.
I have been searching this website for answers to this question, but I couldn't seem to find any. So I want to have the client provide an image to be loaded into a canvas for processing and that's it. So I don't want to save it on the server or on a cloud, but I just want to copy the image to an HTML5 Canvas to be processed from there. Is there a way I can do that without actually saving the file?
I'm not sure if I understand your question. You want that the user can open an image from the client and you load it into a html5 canvas. correct?
If so: you can use an input field of type file. In your code you use URL.createObjectUrl to create object urls from the local selected images. With "Image" you can load the image and in the onload event you draw it to the canvas.
var file = document.getElementById('file'); // the input element of type file
file.onchange = function(e) {
var ctx = document.getElementById('canvas').getContext('2d'); // load context of canvas
var img = new Image();
img.src = URL.createObjectURL(e.target.files[0]); // use first selected image from input element
img.onload = function() {
ctx.drawImage(img, 0, 0); // draw the image to the canvas
}
}
So I'm using google maps and I get the picture so it looks like this
<img id="staticMap"
src="http://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=600x300&maptype=roadmap
&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318
&markers=color:red%7Ccolor:red%7Clabel:C%7C40.718217,-73.998284&sensor=false">
I need to save it. I have found this:
function getBase64FromImageUrl(URL) {
var img = new Image();
img.src = URL;
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL("image/png");
alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));
};
}
But I get this problem:
Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': tainted canvases may not be exported.
I searched for fixes. I found a sample here How to use CORS but still I can't tie these 2 pieces of code together to make it work. Maybe I'm doing it the wrong way and there is a simpler way to do it? I'm trying to save this pic so that I can transfer the data to my server. So maybe someone did something like this and knows how to make .toDataURL() work as I need it?
Unless google serves this image with the correct Access-Control-Allow-Origin header, then you wont be able to use their image in canvas. This is due to not having CORS approval. You can read more about this here, but it essentially means:
Although you can use images without CORS approval in your canvas,
doing so taints the canvas. Once a canvas has been tainted, you can no
longer pull data back out of the canvas. For example, you can no
longer use the canvas toBlob(), toDataURL(), or getImageData()
methods; doing so will throw a security error.
This protects users from having private data exposed by using images
to pull information from remote web sites without permission.
I suggest just passing the URL to your server-side language and using curl to download the image. Be careful to sanitise this though!
EDIT:
As this answer is still the accepted answer, you should check out #shadyshrif's answer, which is to use:
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
This will only work if you have the correct permissions, but will at least allow you to do what you want.
Just use the crossOrigin attribute and pass 'anonymous' as the second parameter
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
This method will prevent you from getting an 'Access-Control-Allow-Origin' error from the server you are accessing to.
var img = new Image();
var timestamp = new Date().getTime();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url + '?' + timestamp;
Try the code below ...
<img crossOrigin="anonymous"
id="imgpicture"
fall-back="images/penang realty,Apartment,house,condominium,terrace house,semi d,detached,
bungalow,high end luxury properties,landed properties,gated guarded house.png"
ng-src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
height="220"
width="200"
class="watermark">
In my case I was using the WebBrowser control (forcing IE 11) and I could not get past the error. Switching to CefSharp which uses Chrome solved it for me.
I had the same error message. I had the file in a simple .html, when I passed the file to php in Apache it worked
html2canvas(document.querySelector('#toPrint')).then(canvas => {
let pdf = new jsPDF('p', 'mm', 'a4');
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298);
pdf.save(filename);
});
if the picture from the 3rd party site didn't set the header for cors ("access-control-allow-origin"), you can never download the picture file through chrome,
even if you use the setAttribute('crossOrigin', 'anonymous');
Here are some suggestions
hack chrome (use an extension, this will only work on your machine)
proxy the image through a service running on your site. The browser will see the domain as your site. This requires your service to request the image from the 3rd party.
By using fabric js we can solve this security error issue in IE.
function getBase64FromImageUrl(URL) {
var canvas = new fabric.Canvas('c');
var img = new Image();
img.onload = function() {
var canvas1 = document.createElement("canvas");
canvas1.width = this.width;
canvas1.height = this.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL({format: "png"});
};
img.src = URL;
}