How to Convert Image URL to Base64
You're given an image URL from an image input and need to convert it to Base64 so you can send it to a web service and save the image locally. The current code you're using doesn't convert the URL to Base64.
To achieve this, you can use the following steps:
<code class="javascript">function getBase64Image(img) { var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); var dataURL = canvas.toDataURL("image/png"); return dataURL.replace(/^data:image\/?[A-z]*;base64,/); }</code>
This function takes an image element (img) as input and returns a Base64-encoded string.
<code class="html"><img id="imageid" src="https://www.google.de/images/srpr/logo11w.png"></code>
<code class="javascript">var base64 = getBase64Image(document.getElementById("imageid"));</code>
This will convert the image to Base64 and store the result in the base64 variable. You can then send the base64 variable to your web service to save the image locally.
The above is the detailed content of How to Convert an Image URL to Base64 in Javascript?. For more information, please follow other related articles on the PHP Chinese website!