如何用JS / PHP解码base64编码的图像? (以前使用Actionscript编码)

时间:2015-08-03 07:42:22

标签: javascript php image actionscript-3 base64

我有一个用base64编码的图像,用ActionScript函数编写:

private static const BASE64_CHARS:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

public static function encodeByteArray(_arg1:ByteArray):String {
   var _local3:Array;
   var _local5:uint;
   var _local6:uint;
   var _local7:uint;
   var _local2 = "";
   var _local4:Array = new Array(4);
   _arg1.position = 0;
   while (_arg1.bytesAvailable > 0) {
        _local3 = new Array();
        _local5 = 0;
        while ((((_local5 < 3)) && ((_arg1.bytesAvailable > 0)))) {
            _local3[_local5] = _arg1.readUnsignedByte();
            _local5++;
        };
        _local4[0] = ((_local3[0] & 252) >> 2);
        _local4[1] = (((_local3[0] & 3) << 4) | (_local3[1] >> 4));
        _local4[2] = (((_local3[1] & 15) << 2) | (_local3[2] >> 6));
        _local4[3] = (_local3[2] & 63);
        _local6 = _local3.length;
        while (_local6 < 3) {
            _local4[(_local6 + 1)] = 64;
            _local6++;
        };
        _local7 = 0;
        while (_local7 < _local4.length) {
            _local2 = (_local2 + BASE64_CHARS.charAt(_local4[_local7]));
            _local7++;
        };
    };
    return (_local2);
}

现在我正在尝试解码(没有成功)JS / PHP中的字符串并返回图像。 这是Actionscript解码函数:

public static function decodeToByteArray(_arg1:String):ByteArray{
    var _local6:uint;
    var _local7:uint;
    var _local2:ByteArray = new ByteArray();
    var _local3:Array = new Array(4);
    var _local4:Array = new Array(3);
    var _local5:uint;
    while (_local5 < _arg1.length) {
        _local6 = 0;
        while ((((_local6 < 4)) && (((_local5 + _local6) < _arg1.length)))) {
            _local3[_local6] = BASE64_CHARS.indexOf(_arg1.charAt((_local5 + _local6)));
            _local6++;
        };
        _local4[0] = ((_local3[0] << 2) + ((_local3[1] & 48) >> 4));
        _local4[1] = (((_local3[1] & 15) << 4) + ((_local3[2] & 60) >> 2));
        _local4[2] = (((_local3[2] & 3) << 6) + _local3[3]);
        _local7 = 0;
        while (_local7 < _local4.length) {
            if (_local3[(_local7 + 1)] == 64){
                break;
            };
            _local2.writeByte(_local4[_local7]);
            _local7++;
        };
        _local5 = (_local5 + 4);
    };
    _local2.position = 0;
    return (_local2);
}

我试图将解码Aactionscript函数转换为JS,但我错过了new ByteArray();我不知道如何管理它。 我需要一种方法将编码的图像字符串解码回图像。 这里是一个图像的base64字符串示例,用“encodeByteArray”函数编码:

sample base64 encoded string

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

要输出base64图像,请使用以下格式:

<img src="data:image/png;base64,ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" />