function get_size(base64) { //确认处理的是png格式的数据 if (base64.substring(0,22) === 'data:image/png;base64,') { // base64 是用四个字符来表示3个字节 // 我们只需要截取base64前32个字符(不计开头那22个字符)便可(24 / 3 * 4) // 这里的data包含12个字符,9个字节,除去第1个字节,后面8个字节就是我们想要的宽度和高度 const data = base64.substring(22 + 20, 22 + 32); const base64Characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; const nums = []; for (const c of data) { nums.push(base64Characters.indexOf(c)); } const bytes = []; for(let i = 0; i < nums.length; i += 4) { bytes.push((nums[i] << 2) + (nums[i+1] >> 4)); bytes.push(((nums[i+1] & 15) << 4) + (nums[i+2] >> 2)); bytes.push(((nums[i+2] & 3) << 6) + nums[i+3]); } const width = (bytes[1] << 24) + (bytes[2] << 16) + (bytes[3] << 8) + bytes[4]; const height = (bytes[5] << 24) + (bytes[6] << 16) + (bytes[7] << 8) + bytes[8]; return { width, height, }; } throw Error('unsupported image type'); }
转载:https://juejin.cn/post/6844904198367084551