Question

im using this below function to encode the image using html5 canvas that im getting from user (here im using local imagefile)

jsfunction

function imgToDataURL(img) {
var canvas = document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
var c = canvas.getContext('2d');
c.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL;
}

its giving localimage cannot be loaded how to overcome this problem & is there any other way to encode the image to base64

Was it helpful?

Solution

To produce data-uris with canvas you need to make sure cross-origin resource sharing (CORS) requirements are fulfilled.

Loading an image from local file:// is considered a different origin than the page (or the effect thereof). If your image simply doesn't load you need to make sure the path to the image is correct as well.

In any case, to be able to load an image that you can later extract from a canvas element as data-uri, you need to make sure that the image is loaded from the same origin using a local installed server such as for example light-weight Mongoose or similar (LAMP/WAMP etc.).

For a public server the same applies but in some cases an external server may allow that images are used cross-origin. In those cases you can request such usage by setting the crossOrigin property on the image to "anonymous" before setting the src. This won't work with local images though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top