Convert image URL to Base64 string
by velo_ninja
HTML
<!DOCTYPE html>
<html>
<body>
<label for="imageUrl">Enter Image URL:</label>
<input type="text" id="imageUrl" placeholder="Paste your image URL here" style="width:100%; margin-bottom:10px;"/>
<button onclick="convertToBase64()">Get Base64</button>
<p><strong>Result (Base64):</strong></p>
<textarea id="output" style="width:100%; height:200px;"></textarea>
<script>
async function convertToBase64() {
const imageUrl = document.getElementById("imageUrl").value; // Get the URL from the input field
if (!imageUrl) {
document.getElementById("output").value = "Please enter a valid image URL.";
return;
}
try {
const response = await fetch(imageUrl);
const blob = await response.blob();
const reader = new FileReader();
reader.onloadend = function () {
const base64data = reader.result;
document.getElementById("output").value = base64data;
};
reader.readAsDataURL(blob);
} catch (err) {
document.getElementById("output").value = "Error: " + err.message;
}
}
</script>
</body>
</html>