window属性:btoa()和atob()

window.btoa()window.atob() 是 Web API 提供的两个函数,用于处理 Base64 编码和解码。Base64 是一种编码方法,可以将二进制数据转换成 ASCII 字符串,这使得二进制数据可以在通常只处理文本的系统之间传输。

window.btoa() 

btoa() 函数用于将二进制数据(通常是字符串)转换为 Base64 编码的字符串。 

返回 Base64 编码的字符串。

// 将字符串 "Hello World" 转换为 Base64 编码
const base64Encoded = btoa("Hello World");
console.log(base64Encoded); // 输出:SGVsbG8gV29ybGQ=

 window.atob()

atob() 函数用于将 Base64 编码的字符串解码回原始的二进制数据(字符串)。 

返回解码后的原始字符串。

// 将 Base64 编码 "SGVsbG8gV29ybGQ=" 解码为原始字符串
const decodedString = atob("SGVsbG8gV29ybGQ=");
console.log(decodedString); // 输出:Hello World

 处理非 ASCII 字符

 对于包含非 ASCII 字符的字符串,你可以使用 encodeURIComponentdecodeURIComponent 来处理:

// 编码包含非 ASCII 字符的字符串
const encoded = btoa(encodeURIComponent("你好,世界!"));
console.log(encoded); // 输出:JUU0JUJEJUEwJUU1JUFEJUE3JUU1JUFFJUExJUU4JThB

// 解码包含非 ASCII 字符的 Base64 编码字符串
const decoded = decodeURIComponent(atob(encoded));
console.log(decoded); // 输出:你好,世界!

btoa()和atob()来处理图片数据 

将图片转换为 Base64 编码
  1. <input type="file"> 获取图片文件: 用户可以通过文件输入选择一个图片文件。

  2. 使用 FileReader API 读取文件内容: 将图片文件读取为二进制数据。

  3. 使用 btoa() 将二进制数据转换为 Base64 编码

<input type="file" id="imageInput" />
<img id="outputImage" />
<script>
  document.getElementById('imageInput').addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = function(e) {
        // 将读取到的二进制数据转换为 Base64 编码
        const base64Image = btoa(e.target.result.split(',')[1]);
        // 显示 Base64 编码的图片
        document.getElementById('outputImage').src = `data:image/png;base64,${base64Image}`;
      };
      reader.readAsDataURL(file); // 读取文件内容并返回 Data URL
    }
  });
</script>
将 Base64 编码的图片转换为二进制数据
  1. 从 Base64 编码的字符串中提取二进制数据

  2. 使用 atob() 将 Base64 编码转换为二进制字符串

  3. 将二进制字符串转换为 Uint8Array 或其他二进制格式

// 假设 base64ImageString 是一个 Base64 编码的图片字符串
const base64ImageString = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';

// 提取 Base64 编码部分
const base64Image = base64ImageString.split(',')[1];

// 使用 atob() 解码 Base64 编码
const binaryString = atob(base64Image);

// 将二进制字符串转换为 Uint8Array
const uint8Array = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
  uint8Array[i] = binaryString.charCodeAt(i);
}

// 使用 Uint8Array 创建 Blob 对象
const blob = new Blob([uint8Array], {type: 'image/png'});

// 创建 URL 对象并使用 Blob URL
const blobUrl = URL.createObjectURL(blob);
document.getElementById('outputImage').src = blobUrl;

END.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

**之火

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值