Home > Web Front-end > JS Tutorial > body text

How to Convert an Image URL to Base64 in Javascript?

Susan Sarandon
Release: 2024-10-31 06:22:30
Original
178 people have browsed it

How to Convert an Image URL to Base64 in Javascript?

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:

  1. Create a JavaScript function to convert the image to Base64:
<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>
Copy after login

This function takes an image element (img) as input and returns a Base64-encoded string.

  1. Get the image element from your HTML:
<code class="html"><img id="imageid" src="https://www.google.de/images/srpr/logo11w.png"></code>
Copy after login
  1. Use the getBase64Image() function to convert the image to Base64:
<code class="javascript">var base64 = getBase64Image(document.getElementById("imageid"));</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!