I have a regular HTML page with some images (just regular <img />
HTML tags). I'd like to get their content, base64 encoded preferably, without the need to redownload the image (ie. it's already loaded by the browser, so now I want the content).
I'd love to achieve that with Greasemonkey and Firefox.
Coming long after, but none of the answers here are entirely correct.
When drawn on a canvas, the passed image is uncompressed + all pre-multiplied.
When exported, its uncompressed or recompressed with a different algorithm, and un-multiplied.
All browsers and devices will have different rounding errors happening in this process
(see Canvas fingerprinting).
So if one wants a base64 version of an image file, they have to request it again (most of the time it will come from cache) but this time as a Blob.
Then you can use a FileReader to read it either as an ArrayBuffer, or as a dataURL.
In addition to matthew's answer, I'd like to say that image.width and image.height return the displayed size of the picture (and crop the image when drawing it to the canvas)
Use naturalWidth and naturalHeight instead, which uses the real-size picture.
See http://www.whatwg.org/specs/web-apps/current-work/multipage/edits.html#dom-img-naturalwidth
A more modern version of kaiido's answer using fetch would be:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
This Function takes the URL then returns the image BASE64
Call it like this :
getBase64FromImageUrl("images/slbltxt.png")
Note: This only works if the image is from the same domain as the page, or has the
crossOrigin="anonymous"
attribute and the server supports CORS. It's also not going to give you the original file, but a re-encoded version. If you need the result to be identical to the original, see Kaiido's answer.You will need to create a canvas element with the correct dimensions and copy the image data with the
drawImage
function. Then you can use thetoDataURL
function to get a data: url that has the base-64 encoded image. Note that the image must be fully loaded, or you'll just get back an empty (black, transparent) image.It would be something like this. I've never written a Greasemonkey script, so you might need to adjust the code to run in that environment.
Getting a JPEG-formatted image doesn't work on older versions (around 3.5) of Firefox, so if you want to support that, you'll need to check the compatibility. If the encoding is not supported, it will default to "image/png".