How to get image data url in JavaScript: It is very simple with HTML5 Canvas API, it provides toDataURL() method. The toDataURL() method of the canvas object converts the canvas drawing into a 64 bit encoded PNG URL.
We have pass “image/jpeg” as argument to toDataURL()
method, to get image data URL in the jpeg format.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function getDataUrl(img) { // Create canvas const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); // Set width and height canvas.width = img.width; canvas.height = img.height; // Draw the image ctx.drawImage(img, 0, 0); return canvas.toDataURL('image/jpeg'); } // Select the image const img = document.querySelector('#my-image'); img.addEventListener('load', function (event) { const dataUrl = getDataUrl(event.currentTarget); console.log(dataUrl); }); |
Output
1 | data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAADSCAMAAABThmYtAAAAXVB |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.