在前端开发中,经常会涉及与后端之间的图片传输,通常情况下可以转码base64,来进行图片上传,也可以通过img标签的src属性展示base64编码格式储存的图片

base64 将 A-Z(ascii 65 – 90) 、a-z(ascii 97 – 122)、0-9(ascii 48 – 57)、+、/ 组成的有序数组作为标准的Base64协议规定

  • 生成base64数组
var base64Array = [];
for (var i = 65; i < 91; i++) {
base64Array.push(String.fromCharCode(i));
}
for (var i = 97; i < 123; i++) {
base64Array.push(String.fromCharCode(i));
}
for (var i = 48; i < 58; i++) {
base64Array.push(String.fromCharCode(i));
}
base64Array.push("+", "/");

一个英文字符占一个字节,一个字节由8位组成

将字符串按每三个字节分成若干组

将每组的24位按照每6位一组分成4组

每组6位,前两位用0补齐形成,4组每组8位,共32位

再将每组的8位2进制转换成10进制,在base64数组中找到对应的值输出

btoa:

function () {
    window.myBtoA = function (testString) {
        var base64Array = [];
        for (var i = 65; i < 91; i++) {
            base64Array.push(String.fromCharCode(i));
        }
        for (var i = 97; i < 123; i++) {
            base64Array.push(String.fromCharCode(i));
        }
        for (var i = 48; i < 58; i++) {
            base64Array.push(String.fromCharCode(i));
        }
        base64Array.push("+", "/");
        var bits = [];
        var newbits = [];
        for (var i = 0; i < testString.length; i++) {
            for (var j = 0; j < 8; j++) {
                bits.push(((testString[i].charCodeAt() >> (7 - j)) & 1));
            }
        }
        while (bits.length) {
            var bit = [0, 0, ...bits.splice(0, 6)];
            if (bit.length !== 8) {
                bit.push(...(new Array(8 - bit.length).fill(0)));
            }
            newbits.push(bit);
        }
        var result = "";
        for (var i of newbits) {
            result += (base64Array[parseInt(i.toString().replace(/,/g, ""), 2)]);
        }
        if (testString.length % 3 === 1) {
            result += "==";
        }
        if (testString.length % 3 === 2) {
            result += "=";
        }
        return result;
    };
})();

118 个评论

  1. Check 1this website to learn how to get free diamonds in cooking fever

    u3iauds11
    This game is more fun when you have unlimited diamonds.If you enjoy phone games like this you ought to check out this guide

    JimRow
  2. Именно сайт informjournal.ru открывает множество возможностей для заработка как в стране, так и за ее границами. Каждый человек может оценить преимущества получения образования, работу терапевта и не только. На сайте постоянно обновляются публикации. О деньгах, интересной информации и разных преимуществах жизни узнать каждый день можно.

    orasxglady
  3. Woah! I’m really enjoying the template/theme of this blog.
    It’s simple, yet effective. A lot of times it’s hard to get that “perfect balance” between superb usability and appearance.
    I must say you’ve done a awesome job with this.
    Additionally, the blog loads extremely fast for me on Chrome.
    Exceptional Blog!

  4. Oh my goodness! Awesome article dude! Many thanks, However I am
    going through issues with your RSS. I don’t know why I can’t join it.
    Is there anybody else having identical RSS problems? Anyone who knows the
    answer will you kindly respond? Thanks!!

  5. Hi! This post couldn’t be written any better! Reading
    through this post reminds me of my good old room mate! He always kept chatting about this.
    I will forward this article to him. Fairly certain he will
    have a good read. Many thanks for sharing!

  6. Howdy I am so thrilled I found your site, I really found you
    by accident, while I was looking on Bing for something else, Regardless I am
    here now and would just like to say many thanks for a fantastic post and a all round
    exciting blog (I also love the theme/design), I
    don’t have time to look over it all at the minute but I have bookmarked it and also added your RSS feeds, so when I have time I will be back to read a great deal more,
    Please do keep up the excellent jo.

  7. Appreciating the dedication you put into your blog and in depth information you offer.
    It’s good to come across a blog every once in a while that isn’t the same unwanted rehashed information. Fantastic read!
    I’ve bookmarked your site and I’m including your RSS feeds to my Google account.

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注