जावास्क्रिप्ट का उपयोग करके एचटीएमएल पेज टैग से डेटा यूआरआई में छवि को कनवर्ट करने के लिए, आपको सबसे पहले कैनवास तत्व बनाना होगा, इसकी चौड़ाई और ऊंचाई को छवि के बराबर सेट करना होगा, उस पर छवि बनाएं और अंत में उस पर toDataURL विधि को कॉल करें।
यह छवि के बेस 64 एन्कोडेड डेटा यूआरआई को वापस कर देगा। उदाहरण के लिए, यदि आपके पास my-image आईडी वाली कोई छवि है, तो आप निम्न का उपयोग कर सकते हैं -
उदाहरण
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);
}); आउटपुट
यह आउटपुट देगा -
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAADSCAMAAABThmYtAAAAXVB