Created
October 17, 2020 13:24
-
-
Save muzi131313/04b9b03dbe36b086fe7d901be4b066a7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var setContextOption = (newCtx, { | |
smoothEnabled = true, | |
smoothQuality = 'high' | |
} = {}) => { | |
newCtx.imageSmoothingEnabled = smoothEnabled // 图片平滑, 默认为 true | |
newCtx.msImageSmoothingEnabled = smoothEnabled | |
newCtx.webkitImageSmoothingEnabled = smoothEnabled | |
newCtx.mozImageSmoothingEnabled = smoothEnabled | |
newCtx.imageSmoothingQuality = smoothQuality // 调整平滑质量 | |
newCtx.msImageSmoothingQuality = smoothQuality | |
newCtx.webkitImageSmoothingQuality = smoothQuality | |
newCtx.mozImageSmoothingQuality = smoothQuality | |
} | |
// 原图url: https://www.baidu.com/img/bd_logo1.png | |
// 使用此方法获取base64后,体积为 15kb,原图为7.9kb | |
var getBaseInfoByImageInfo = (imageURL, { | |
targetWidth, | |
targetHeight, | |
} = {}) => { | |
return new Promise((resolve, reject) => { | |
let image = new Image(targetWidth, targetHeight) | |
image.crossOrigin = 'anonymous' | |
if (targetWidth && targetHeight) { | |
image.width = targetWidth | |
image.height = targetHeight | |
} | |
image.onload = async function() { | |
try { | |
const newCanvas = document.createElement('canvas') | |
const newCtx = newCanvas.getContext('2d') | |
newCanvas.width = targetWidth || image.naturalWidth | |
newCanvas.height = targetHeight || image.naturalHeight | |
setContextOption(newCtx) | |
console.log('getBaseInfoByImageInfo() image: ', image.naturalWidth, image.naturalHeight) | |
newCtx.drawImage(image, 0, 0, image.naturalWidth, image.naturalHeight, 0, 0, newCanvas.width, newCanvas.height) | |
const base64 = newCanvas.toDataURL('image/png') | |
resolve(base64) | |
} | |
catch (e) { | |
console.error(e) | |
reject(e) | |
} | |
} | |
image.onerror = function(e) { | |
reject(e) | |
} | |
image.src = imageURL | |
}) | |
} | |
var getFileSizeByBase64 = baseStr => { | |
// 去除 base64 前缀,例如: data:image/png;base64, | |
var tag = 'base64,' | |
var tagIndex = baseStr.indexOf(tag) | |
baseStr = baseStr.substring(tagIndex + tag.length) | |
// 去掉base64编码中的 = | |
var eqTagIndex = baseStr.indexOf('=') | |
baseStr = eqTagIndex != -1 | |
? baseStr.substring(0, eqTagIndex) | |
: baseStr | |
// 计算文件流大小 | |
var strLen = baseStr.length | |
var fileSize = strLen - (strLen/8)*2 | |
return fileSize | |
} | |
// doc: https://my.oschina.net/peachyy/blog/1809638 | |
getBaseInfoByImageInfo('https://www.baidu.com/img/bd_logo1.png').then(base64 => { | |
var fileSize = getFileSizeByBase64(base64) | |
window.base64Info = base64 | |
console.log('fileSize: ', fileSize) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment