今天試了用js把base64編碼格式的圖片進(jìn)行壓縮,記錄一下:
base64圖片轉(zhuǎn)換地址?
base64圖片轉(zhuǎn)換網(wǎng)址
?代碼如下
js:
$(document).ready(function(){
compressImg(targetObj.src, 0.5, useImg, targetObj)
});
let targetObj = {
// base64字符串 太大了,刪掉了,可以自己替換
src: ''
}
function compressImg (base64, multiple, useImg, targetObj) {
// 第一個(gè)參數(shù)就是需要加密的base65,
// 第二個(gè)是壓縮系數(shù) 0-1,
// 第三個(gè)壓縮后的回調(diào) 用來獲取處理后的 base64
if (!base64) {
return
}
// const _this = this
const length = base64.length / 1024
// 壓縮方法
let newImage = new Image()
let quality = 0.6 // 壓縮系數(shù)0-1之間
newImage.src = base64
newImage.setAttribute('crossOrigin', 'Anonymous') // url為外域時(shí)需要
let imgWidth,
imgHeight
let w = undefined
newImage.onload = function () {
// 這里面的 this 指向 newImage
// 通過改變圖片寬高來實(shí)現(xiàn)壓縮
w = this.width * multiple
imgWidth = this.width
imgHeight = this.height
let canvas = document.createElement('canvas')
let ctx = canvas.getContext('2d')
if (Math.max(imgWidth, imgHeight) > w) {
if (imgWidth > imgHeight) {
canvas.width = w
// 等比例縮小
canvas.height = w * (imgHeight / imgWidth)
} else {
canvas.height = w
// 等比例縮小
canvas.width = w * (imgWidth / imgHeight)
}
} else {
canvas.width = imgWidth
canvas.height = imgHeight
// quality 設(shè)置轉(zhuǎn)換為base64編碼后圖片的質(zhì)量,取值范圍為0-1 沒什么壓縮效果
// 還是得通過設(shè)置 canvas 的寬高來壓縮
quality = 0.6
}
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(this, 0, 0, canvas.width, canvas.height) // // 這里面的 this 指向 newImage
let smallBase64 = canvas.toDataURL('image/jpeg', quality) // 壓縮語句
// 如想確保圖片壓縮到自己想要的尺寸,如要求在50-150kb之間,請(qǐng)加以下語句,quality初始值根據(jù)情況自定
// while (smallBase64.length / 1024 > 150) {
// quality -= 0.01;
// smallBase64 = canvas.toDataURL("image/jpeg", quality);
// }
// 防止最后一次壓縮低于最低尺寸,只要quality遞減合理,無需考慮
// while (smallBase64.length / 1024 < 50) {
// quality += 0.001;
// smallBase64 = canvas.toDataURL("image/jpeg", quality);
// }
// 必須通過回調(diào)函數(shù)返回,否則無法及時(shí)拿到該值,回調(diào)函數(shù)異步執(zhí)行
console.log(`壓縮前:${length}KB`)
console.log(`壓縮后:${smallBase64.length / 1024} KB`)
useImg(smallBase64, targetObj)
}
}
function useImg (base64, targetObj) {
// targetObj 通過值引用的特性 用處理后的 base64 覆蓋 處理前的 base63
console.log('壓縮后的 base64 :', base64)
$("#img").attr("src", base64);
targetObj.src = base64
}
html?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.7.0.min.js"></script>
<script type="text/javascript" src="my.js"></script>
</head>
<body>
<h1>測(cè)試</h1>
<img id="img" src="">
</body>
</html>
測(cè)試效果
文章來源:http://www.zghlxwxcb.cn/news/detail-524970.html
?壓縮包已經(jīng)上傳資源包中,有需要可以下載,下完即用文章來源地址http://www.zghlxwxcb.cn/news/detail-524970.html
到了這里,關(guān)于js壓縮base64圖片的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!