Regex to parse image data URI

后端 未结 5 2198
野性不改
野性不改 2021-02-07 04:29

If I have :



        
5条回答
  •  无人及你
    2021-02-07 05:03

    Data URI's have a bit of complexity to them, they can contain params, media type, etc... and sometimes you need to know this info, not just the data.

    To parse a data URI and extract all of the relevant parts, try this:

    /**
     * Parse a data uri and return an object with information about the different parts
     * @param {*} data_uri 
     */
    function parseDataURI(data_uri) {
        let regex = /^\s*data:(?(?[a-z\-]+\/[a-z\-\+]+)(?(;[a-z\-]+\=[a-z\-]+)*))?(?;base64)?,(?[a-z0-9\!\$\&\'\,\(\)\*\+\,\;\=\-\.\_\~\:\@\/\?\%\s]*\s*)$/i;
        let result = regex.exec(data_uri);
        let info = {
            media_type: result.groups.media_type,
            mime_type: result.groups.mime_type,
            params: result.groups.params,
            encoding: result.groups.encoding,
            data: result.groups.data
        }
        if(info.params)
            info.params = Object.fromEntries(info.params.split(';').slice(1).map(param => param.split('=')));
        if(info.encoding)
            info.encoding = info.encoding.replace(';','');
        return info;
    }

    This will give you an object that has all the relevant bits parsed out, and the params as a dictionary {foo: baz}.

    Example (mocha test with assert):

    describe("Parse data URI", () => {
        it("Should extract data URI parts correctly",
            async ()=> {
                let uri = 'data:text/vnd-example+xyz;foo=bar;bar=baz;base64,R0lGODdh';
                let info = parseDataURI(uri);
                assert.equal(info.media_type,'text/vnd-example+xyz;foo=bar;bar=baz');
                assert.equal(info.mime_type,'text/vnd-example+xyz');
                assert.equal(info.encoding, 'base64');
                assert.equal(info.data, 'R0lGODdh');
                assert.equal(info.params.foo, 'bar');
                assert.equal(info.params.bar, 'baz');
            }
        );
    });

提交回复
热议问题