PNG 이미지를 Base64 문자열로 인코딩할 수 있는 PHP 스크립트를 가지고 있습니다.
JavaScript를 사용하여 같은 작업을 하고 싶습니다.파일을 여는 방법은 알지만 인코딩하는 방법은 잘 모르겠어요.바이너리 데이터를 사용하는 데 익숙하지 않습니다.
질문에 대한 답변
및 를 사용하여 base64 인코딩으로 변환하거나 base64 인코딩에서 변환할 수 있습니다.
이러한 함수의 수용/반환에 관한 코멘트에 혼선이 있는 것 같습니다.
btoa()
는 각 문자가 8비트바이트를 나타내는 스트링을 받아들입니다.8비트로 나타낼 수 없는 문자가 포함된 스트링을 전달하면 스트링이 끊어질 수 있습니다.실제로 문자열을 바이트 배열로 취급하는 경우에는 문제가 없지만 다른 작업을 수행하려는 경우에는 먼저 인코딩해야 합니다.atob()
각 문자가 8비트바이트를 나타내는 “문자열”을 반환합니다.즉, 그 값은 다음 중 하나입니다.0
그리고.0xff
이것은 ASCII를 의미하는 것은 아닙니다.아마도 이 기능을 사용하고 있다면 텍스트가 아닌 바이너리 데이터로 작업할 수 있을 것입니다.
다음 항목도 참조하십시오.
여기 댓글들은 대부분 구식이야.아마 둘 다 쓸 수 있을 거예요.btoa()
그리고.atob()
단, 실제로 오래된 브라우저를 지원하지 않는 한.
여기를 체크해 주세요.
여기서부터:
/** * *
Base64 encode / decode *
http://www.webtoolkit.info/ * **/ var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4)
(chr2 >> 4);
enc3 = ((chr2 & 15) << 2)
(chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2)
(enc2 >> 4);
chr2 = ((enc2 & 15) << 4)
(enc3 >> 2);
chr3 = ((enc3 & 3) << 6)
enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/rn/g,"n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6)
192);
utftext += String.fromCharCode((c & 63)
128);
}
else {
utftext += String.fromCharCode((c >> 12)
224);
utftext += String.fromCharCode(((c >> 6) & 63)
128);
utftext += String.fromCharCode((c & 63)
128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6)
(c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12)
((c2 & 63) << 6)
(c3 & 63));
i += 3;
}
}
return string;
} }
또, 「JavaScript base64 encoding」을 검색하면, 그 외의 옵션이 많이 표시됩니다.이것이 첫 번째 옵션입니다.
Internet Explorer 10 이상
// Define the string var string = 'Hello World!';
// Encode the String var encodedString = btoa(string); console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
// Decode the String var decodedString = atob(encodedString); console.log(decodedString); // Outputs: "Hello World!"
크로스 브라우저
// Create Base64 Object var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4 r>>4;u=(r&15)<<2 i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9+/=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2 o>>4;r=(o&15)<<4 u>>2;i=(u&3)<<6 a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/rn/g,"n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6 192);t+=String.fromCharCode(r&63 128)}else{t+=String.fromCharCode(r>>12 224);t+=String.fromCharCode(r>>6&63 128);t+=String.fromCharCode(r&63 128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6 c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12 (c2&63)<<6 c3&63);n+=3}}return t}}
// Define the string var string = 'Hello World!';
// Encode the String var encodedString = Base64.encode(string); console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
// Decode the String var decodedString = Base64.decode(encodedString); console.log(decodedString); // Outputs: "Hello World!"
Node.js 사용 시
Node.js에서 일반 텍스트를 base64로 인코딩하는 방법은 다음과 같습니다.
//Buffer() requires a number, array or string as the first parameter, and an optional encoding type as the second parameter. // The default is "utf8". Possible encoding types are "ascii", "utf8", "ucs2", "base64", "binary", and "hex" var b = Buffer.from('JavaScript'); // If we don't use toString(), JavaScript assumes we want to convert the object to utf8. // We can make it convert to other formats by passing the encoding type to toString(). var s = b.toString('base64');
base64 부호화 문자열을 디코딩하는 방법은 다음과 같습니다.
var b = new Buffer('SmF2YVNjcmlwdA==', 'base64') var s = b.toString();
Dojo.js와 함께
dojox.encoding.base64를 사용하여 바이트 배열을 인코딩하려면 다음 절차를 수행합니다.
var str = dojox.encoding.base64.encode(myByteArray);
Base64로 인코딩된 문자열을 디코딩하려면:
var bytes = dojox.encoding.base64.decode(str)
바우어 설치 각도 베이스 64
<script src="bower_components/angular-base64/angular-base64.js"></script>
angular
.module('myApp', ['base64'])
.controller('myController', [
'$base64', '$scope',
function($base64, $scope) {
$scope.encoded = $base64.encode('a string');
$scope.decoded = $base64.decode('YSBzdHJpbmc='); }]);
Sunny의 코드는 Internet Explorer 7에서 “this”에 대한 참조가 있기 때문에 끊어지는 것을 제외하고는 훌륭합니다.이러한 참조를 “Base64″로 대체하여 수정했습니다.
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4)
(chr2 >> 4);
enc3 = ((chr2 & 15) << 2)
(chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
Base64._keyStr.charAt(enc1) + Base64._keyStr.charAt(enc2) +
Base64._keyStr.charAt(enc3) + Base64._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (i < input.length) {
enc1 = Base64._keyStr.indexOf(input.charAt(i++));
enc2 = Base64._keyStr.indexOf(input.charAt(i++));
enc3 = Base64._keyStr.indexOf(input.charAt(i++));
enc4 = Base64._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2)
(enc2 >> 4);
chr2 = ((enc2 & 15) << 4)
(enc3 >> 2);
chr3 = ((enc3 & 3) << 6)
enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/rn/g,"n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6)
192);
utftext += String.fromCharCode((c & 63)
128);
}
else {
utftext += String.fromCharCode((c >> 12)
224);
utftext += String.fromCharCode(((c >> 6) & 63)
128);
utftext += String.fromCharCode((c & 63)
128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6)
(c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12)
((c2 & 63) << 6)
(c3 & 63));
i += 3;
}
}
return string;
} }
사용할 수 있습니다.btoa
(Base64로) 및atob
(Base64부터).
Internet Explorer 9 이하의 경우 jquery-base64 플러그인을 사용해 보십시오.
$.base64.encode("this is a test"); $.base64.decode("dGhpcyBpcyBhIHRlc3Q=");