方法实现
/** * 从base64编码中解析图片信息 * @param {String} base64 * @returns {Object} */ function parseBase64(base64) { let re = new RegExp('data:(?<type>.*?);base64,(?<data>.*)') let res = re.exec(base64) if (res) { return { type: res.groups.type, ext: res.groups.type.split('/').slice(-1)[0], data: res.groups.data, } } }
示例
let base64 = 'data:image/gif;base64,R0lGODlhAQABAPcAAAuvCwu1Cwy6DAy/DA' let info = parseBase64(base64) console.log(info);
输出
{ type: 'image/gif', ext: 'gif', data: 'R0lGODlhAQABAPcAAAuvCwu1Cwy6DAy/DA' }