如何使用 JavaScript 將影像轉換為 Base64 字串?
要使用 JavaScript 將影像轉換為 base64 字串,請使用 FileReader API。你可以嘗試執行以下程式碼來獲取影像的 base64 字串 -
示例
<!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://tutorialspoint.tw/videotutorials/images/tutor_connect_home.jpg', function(dataUrl) { document.write('Result in string:', dataUrl) }) </script> </body> </html>
廣告