迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

使用 JavaScript 将图像转换为 Base64 字符串

作者:迹忆客 最近更新:2024/03/16 浏览次数:

JavaScript 具有将图像 URL 或图像从本地 PC 转换为 base64 字符串的约定。该字符串可以有大量的符号和字母。

我们将讨论创建一个 canvas 元素,将图像加载到其中,并使用 toDataURL 来显示字符串表示。我们还将尝试使用 file reader 选项来获取 base64 字符串表示形式。


在 JavaScript 中使用 canvas 将图像转换为 Base64 字符串

在这种情况下,我们创建一个 canvas 元素并定义它的维度 - 我们将存储字符串表示形式的 dataURL

我们将添加来自在线资源的随机图像,为了避免安全问题,我们将确保 object.crossOrigin = 'Anonymous'。最后,我们的回调函数会将 dataURL 传递给 toDataURL 函数,以提醒窗口预览相应图像的 base64 字符串。

代码片段:

<!DOCTYPE html>
<html lang="en">
  
<head>
  <title>Test</title>
  <style>
    img{
      height: 200px;
    }
  </style>
</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>

输出:


在 JavaScript 中使用 FileReader 将图像转换为 Base64 字符串

对于文件读取约定,我们将动态初始化一个新对象。该对象将触发 onload 方法并提取 base64 字符串。我们的 input 元素通过上传从本地计算机获取图像。

代码片段:

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
    <input type="file" name="" id="fileId" 
        onchange="Uploaded()">
    <br><br>
    <button onclick="display()">
        Display String
    </button>
</body>
</html>
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);
}

输出:

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便