使用 Javascript 将图像转换为 Base64 数据 URL
javascriptobject oriented programmingprogramming
JavaScript 有一个将图像 URL 或本地 PC 图像转换为 base64 字符串的约定。此字符串可以包含各种符号和字母。这里解释了如何制作画布元素、将图像加载到其中以及如何使用 toDataURL 显示字符串表示。为了获取 base64 字符串表示,我们还将使用文件读取器选项。
在这种情况下,它被创建为画布元素,并将指定其尺寸。将存储字符串表示的 dataURL。我们将从在线来源添加随机图像并确保对象避免安全问题。'Anonymous' 作为 crossOrigin 最后,我们的回调函数将 dataURL 传递给 toDataURL 函数,以通知窗口相应图像的 base64 字符串已准备好进行预览。
示例 1
以下示例尝试在 JavaScript 中将图像转换为 Base64 数据 URL −
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Get URL i</title> </head> <body> <img src="https://images.unsplash.com/photo-1606115915090-be18fea23ec7?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=465&q=80" id="myImg"> <script> function toDataURL(src, callback){ var image = new Image(); image.crossOrigin = 'Anonymous'; image.onload = function(){ var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); canvas.height = this.naturalHeight; canvas.width = this.naturalWidth; context.drawImage(this, 0, 0); var dataURL = canvas.toDataURL('image/jpeg'); callback(dataURL); }; image.src = src; } toDataURL('https://images.unsplash.com/photo-1606115915090-be18fea23ec7?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=465&q=80', function(dataURL){ alert(dataURL); }) </script> </body> </html>
示例 2
以下是将图像转换为 URL 的示例 -
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Get URL i</title> <script> var base64String = ""; function Uploaded() { var file = document.querySelector( 'input[type=file]')['files'][0]; var reader = new FileReader(); reader.onload = function () { base64String = reader.result.replace("data:", "") .replace(/^.+,/, ""); imageBase64Stringsep = base64String; } reader.readAsDataURL(file); } function display() { console.log("Base64String about to be printed"); alert(base64String); } </script> </head> <body> <input type="file" name="" id="fileId" onchange="Uploaded()"> <br><br> <button onclick="display()"> Display String </button> </body> </html>