在前端开发中,经常会涉及与后端之间的图片传输,通常情况下可以转码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;
    };
})();

125 个评论

  1. Клиенты, знакомые с работой Михаила Михайловича, выбирают его техцентр благодаря неизменно высокому качеству обслуживания и возможности лично получить консультацию специалиста высокого класса. За годы работы Михаил Михайлович создал уникальную клиентскую базу. avtomm71.ru

  2. It is perfect time to make some plans for the longer term and it is time to
    be happy. I have learn this submit and if I could I want to
    recommend you few interesting things or advice.
    Maybe you can write next articles referring to this article.
    I want to learn even more issues approximately it!

  3. Hi there! I understand this is sort of off-topic however
    I had to ask. Does operating a well-established blog such as
    yours require a large amount of work? I am completely new
    to operating a blog but I do write in my journal daily.
    I’d like to start a blog so I can easily share my experience
    and thoughts online. Please let me know if you have any suggestions or
    tips for brand new aspiring blog owners. Thankyou!

  4. I’m not sure where you’re getting your info, however good topic.
    I must spend a while studying more or working out more.
    Thanks for excellent information I was searching for
    this information for my mission.

  5. I know this if off topic but I’m looking
    into starting my own weblog and was curious what all is required to get setup?

    I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very internet smart so I’m not 100% certain.
    Any recommendations or advice would be greatly appreciated.
    Thanks

  6. 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!

  7. 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!!

  8. 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!

  9. 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.

  10. 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.

发表评论

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