如何使用 JavaScript 将图像转换为 base64 字符串?

javascriptobject oriented programmingfront end technology更新于 2024/7/23 5:00:17

要使用 JavaScript 将图像转换为 base64 字符串,请使用 FileReader API。您可以尝试运行以下代码来获取图像的 base64string −

示例

<!DOCTYPE html>
<html>
   <body>
      <script>
         function toDataURL(url, callback) {
            var httpRequest = new XMLHttpRequest();
            httpRequest.onload = function() {
               var fileReader = new FileReader();
                  fileReader.onloadend = function() {
                     callback(fileReader.result);
                  }
                  fileReader.readAsDataURL(httpRequest.response);
            };
            httpRequest.open('GET', url);
            httpRequest.responseType = 'blob';
            httpRequest.send();
         }
         toDataURL('https://www.tutorialspoint.com/videotutorials/images/tutor_connect_home.jpg', function(dataUrl) {
         document.write('Result in string:', dataUrl)
      })
      </script>
   </body>
</html>

相关文章


有用资源