Search code examples
javascriptimagedata-url

Looking for toDataUrl guidance


Cut to the chase... I'd like to take a local image file, use javascript to create a dataurl value from that image. I'm not totally sure how to go about doing that. I have looked at a bunch of code examples and i'm not real sure on what exactly they are doing with the canvas stuff. Also can I even hope to access local files for this? I am willing to bet that, that would be a security risk and javascript wouldn't be able to reach out past it's sandbox.

Essentially, with REAL paraphrased JS, this is what i'm looking to do...

var imgTest = "/tmp/prev/localimage.jpeg";
var imgTest = imgTest.toDataUrl;
document.write(imgTest);

The end result hopefully being a dataurl string printed to the webpage, "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQE..."

Does this make sense? I just want that dataurl information in a variable.

Thanks so much for your great advice StackOverflow!


Solution

  • "The toDataURL() method requires that any images drawn onto the canvas are hosted on a web server with the same domain as the code executing it. If this condition is not met, a SECURITY_ERR exception is thrown." Source

    To me, this sounds like it will not work with local files and is used to generate encoded image data from content drawn on an HTML5 canvas.

    Looking at the Mozilla documentation confirms that toDataURL() is a function specifically for the canvas object, not an image object.

    If I understand correctly, you may be able to draw the image on a canvas of the same dimensions and then use the toDataURL() method to generate your encoded data. This, of course, assuming the image file resides in the same location as the JavaScript code.