Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Javascript

จะแปลงรูปภาพเป็นสตริง base64 โดยใช้ JavaScript ได้อย่างไร


ในการแปลงรูปภาพเป็นสตริง base64 โดยใช้ JavaScript ให้ใช้ 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>