我有一个PHP脚本,可以将PNG图像编码为Base64字符串。
我想用JavaScript做同样的事情。我知道如何打开文件,但我不知道如何进行编码。我不习惯使用二进制数据。
我有一个PHP脚本,可以将PNG图像编码为Base64字符串。
我想用JavaScript做同样的事情。我知道如何打开文件,但我不知道如何进行编码。我不习惯使用二进制数据。
当前回答
请注意,这不适用于原始的Unicode字符串!请参阅这里的Unicode部分。
编码语法
var encodedData = window.btoa(stringToEncode);
解码语法
var decodedData = window.atob(encodedData);
其他回答
您可以使用btoa()和atob()来转换base64编码。
关于这些函数接受/返回什么,评论中似乎有一些混淆,所以…
btoa() accepts a “string” where each character represents an 8-bit byte – if you pass a string containing characters that can’t be represented in 8 bits, it will probably break. This isn’t a problem if you’re actually treating the string as a byte array, but if you’re trying to do something else then you’ll have to encode it first. atob() returns a “string” where each character represents an 8-bit byte – that is, its value will be between 0 and 0xff. This does not mean it’s ASCII – presumably if you’re using this function at all, you expect to be working with binary data and not text.
参见:
如何使用Javascript和XMLHttpRequest加载二进制图像数据?
这里的大多数评论都过时了。您可能同时使用btoa()和atob(),除非您支持非常过时的浏览器。
检查:
https://caniuse.com/?search=atob https://caniuse.com/?search=btoa
如果你想简单快速地编码base 64,而不考虑可能的兼容性问题,你可以使用turbocommons库。只需下载压缩后的js文件并编写以下代码:
<script src="../yourpathtothelibrary/turbocommons-es5.js"></script>
<script>
var ConversionUtils = org_turbocommons.ConversionUtils;
ConversionUtils.stringToBase64('hello');
</script>
你可以在这里查看库是如何完成的代码:
https://github.com/edertone/TurboCommons/blob/master/TurboCommons-TS/src/main/ts/utils/ConversionUtils.ts
更多信息:
https://turboframework.org/en/blog/2022-10-26/encode-decode-base64-strings-javascript-typescript-php
你可以在这里在线测试:
https://turboframework.org/en/app/stringutils/base64-encode
我需要一个UTF-8字符串编码为Base64为我的一个项目。这里的大多数答案似乎在转换为UTF-8时不能正确处理UTF-16代理对,因此,为了完成,我将发布我的解决方案:
function strToUTF8Base64(str) {
function decodeSurrogatePair(hi, lo) {
var resultChar = 0x010000;
resultChar += lo - 0xDC00;
resultChar += (hi - 0xD800) << 10;
return resultChar;
}
var bytes = [0, 0, 0];
var byteIndex = 0;
var result = [];
function output(s) {
result.push(s);
}
function emitBase64() {
var digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
'abcdefghijklmnopqrstuvwxyz' +
'0123456789+/';
function toDigit(value) {
return digits[value];
}
// --Byte 0-- --Byte 1-- --Byte 2--
// 1111 1122 2222 3333 3344 4444
var d1 = toDigit(bytes[0] >> 2);
var d2 = toDigit(
((bytes[0] & 0x03) << 4) |
(bytes[1] >> 4));
var d3 = toDigit(
((bytes[1] & 0x0F) << 2) |
(bytes[2] >> 6));
var d4 = toDigit(
bytes[2] & 0x3F);
if (byteIndex === 1) {
output(d1 + d2 + '==');
}
else if (byteIndex === 2) {
output(d1 + d2 + d3 + '=');
}
else {
output(d1 + d2 + d3 + d4);
}
}
function emit(chr) {
bytes[byteIndex++] = chr;
if (byteIndex == 3) {
emitBase64();
bytes[0] = 0;
bytes[1] = 0;
bytes[2] = 0;
byteIndex = 0;
}
}
function emitLast() {
if (byteIndex > 0) {
emitBase64();
}
}
// Converts the string to UTF8:
var i, chr;
var hi, lo;
for (i = 0; i < str.length; i++) {
chr = str.charCodeAt(i);
// Test and decode surrogate pairs in the string
if (chr >= 0xD800 && chr <= 0xDBFF) {
hi = chr;
lo = str.charCodeAt(i + 1);
if (lo >= 0xDC00 && lo <= 0xDFFF) {
chr = decodeSurrogatePair(hi, lo);
i++;
}
}
// Encode the character as UTF-8.
if (chr < 0x80) {
emit(chr);
}
else if (chr < 0x0800) {
emit((chr >> 6) | 0xC0);
emit(((chr >> 0) & 0x3F) | 0x80);
}
else if (chr < 0x10000) {
emit((chr >> 12) | 0xE0);
emit(((chr >> 6) & 0x3F) | 0x80);
emit(((chr >> 0) & 0x3F) | 0x80);
}
else if (chr < 0x110000) {
emit((chr >> 18) | 0xF0);
emit(((chr >> 12) & 0x3F) | 0x80);
emit(((chr >> 6) & 0x3F) | 0x80);
emit(((chr >> 0) & 0x3F) | 0x80);
}
}
emitLast();
return result.join('');
}
注意,代码没有经过彻底的测试。我测试了一些输入,包括strToUTF8Base64('衠衢蠩蠨'),并将其与在线编码工具(https://www.base64encode.org/)的输出进行了比较。
这是一个helper funktion来编码到base64url:
base64url (s) {
var to64url = btao(s);
// Replace non-url compatible chars with base64url standard chars and remove leading =
return to64url.replace(/\+/g, '_').replace(/\//g, '-').replace(/=+$/g, '');
}
虽然还有一些工作要做,但如果你想要一个高性能的本地解决方案,可以使用一些HTML5函数。
如果你可以把你的数据放到一个Blob中,那么你可以使用FileReader.readAsDataURL()函数来获得一个data:// URL,并砍掉它的前面来获得Base64数据。
你可能必须做进一步的处理,但urldecode数据,因为我不确定是否+字符转义或不为数据:// URL,但这应该是相当微不足道的。