項(xiàng)目是用uniapp開發(fā)的,當(dāng)時(shí)只是做App端,后來項(xiàng)目擴(kuò)展到H5端, uniapp框架可以跨平臺(tái)所以移動(dòng)端和H5使用的是一套代碼
上傳頭像的時(shí)候要求圖片的大小在2MB一下,所以要壓縮圖片,App端當(dāng)時(shí)使用的是uni.compressImage(OBJECT)壓縮的(詳情見:https://uniapp.dcloud.net.cn/api/media/image.html#compressimage 但是H5不兼容;
先搞定H5的壓縮吧!網(wǎng)上一搜一大把
/**
* H5壓縮 二分查找算法來找到一個(gè)合適的圖像質(zhì)量系數(shù),使得壓縮后的圖片文件大小接近于目標(biāo)大小
* @param {Object} imgSrc 圖片url
* @param {Object} callback 回調(diào)設(shè)置返回值
* */
export function compressH5(fileItem, targetSizeKB, initialQuality = 1.0) {
const maxQuality = 1.0;
const minQuality = 0.0;
const tolerance = 0.01; // 根據(jù)需要調(diào)整公差
return new Promise((resolve, reject) => {
const binarySearch = (min, max) => {
const midQuality = (min + max) / 2;
const reader = new FileReader();
reader.readAsDataURL(fileItem);
reader.onload = function () {
const img = new Image();
img.src = this.result;
img.onload = function () {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
// 使用異步的 toBlob 方法
canvas.toBlob(async (blob) => {
const fileSizeKB = blob.size / 1024;
if (Math.abs(fileSizeKB - targetSizeKB) < tolerance || max - min < tolerance) {
// 當(dāng)前質(zhì)量足夠接近目標(biāo)大小,使用當(dāng)前質(zhì)量解析
resolve(URL.createObjectURL(blob));
} else if (fileSizeKB > targetSizeKB) {
// 如果文件大小太大,降低質(zhì)量,繼續(xù)二分查找
binarySearch(min, midQuality);
} else {
// 如果文件大小太小,增加質(zhì)量,繼續(xù)二分查找
binarySearch(midQuality, max);
}
}, 'image/jpeg', midQuality);
};
};
reader.onerror = function (error) {
reject(error);
};
};
// 開始二分查找
binarySearch(minQuality, maxQuality);
});
}
調(diào)用方法
chooseImg1() {
uni.chooseImage({
count: 1, //默認(rèn)9
sizeType:['compressed'],
success: (chooseImageRes) => {
const tempFilePaths = chooseImageRes.tempFilePaths;
const filePath = tempFilePaths[0];
// 獲取圖片文件大小
uni.getFileInfo({
filePath: filePath,
success: (fileInfo) => {
const fileSize = fileInfo.size; // 圖片文件大小,單位為B
// 判斷圖片大小是否超過200KB
if (fileSize > 200 * 1024) {
//#ifdef H5
//h5壓縮圖片
const targetSizeKB = 150; // 設(shè)置目標(biāo)文件大小,單位為KB,根據(jù)需求調(diào)整
compressH5(chooseImageRes.tempFiles[0],targetSizeKB).then(file => {
console.log('file 222 = ', file)
this.uploadCompressedImage(file);
}).catch(err => {
console.log('catch', err)
})
//#endif
//#ifdef APP-PLUS || MP-WEIXIN
// 如果超過200KB,進(jìn)行壓縮
uni.compressImage({
src: filePath,
quality: 10, // 設(shè)置壓縮質(zhì)量(0-100)- 根據(jù)需求進(jìn)行調(diào)整
success: (compressRes) => {
// 壓縮成功后的邏輯
this.uploadCompressedImage(compressRes.tempFilePath);
},
fail: (err) => {
console.error('壓縮圖片失敗:', err);
uni.showToast({
title: '壓縮圖片失敗,請(qǐng)重試',
icon: 'none'
});
}
});
//#endif
} else {
// 如果未超過200KB,直接上傳原圖
this.uploadCompressedImage(filePath);
}
},
fail: (err) => {
console.error('獲取文件信息失敗:', err);
uni.showToast({
title: '獲取文件信息失敗,請(qǐng)重試',
icon: 'none'
});
}
});
},
fail: (err) => {
console.error('選擇圖片失敗:', err);
uni.showToast({
title: '選擇圖片失敗,請(qǐng)重試',
icon: 'none'
});
}
});
},
uploadCompressedImage(filePath) {
uni.uploadFile({
url: `${this.$VUE_APP_API_URL}/common/image/image/upload/faceImg`,
filePath: filePath,
name: 'file',
header: {
'Authorization': uni.getStorageSync('X-Token'), // 修改為你的訪問令牌
},
success: (res) => {
uni.hideLoading(); // 隱藏 loading
if (res.statusCode === 200) {
console.log('上傳成功:', res.data);
const responseData = JSON.parse(res.data); // 解析返回的數(shù)據(jù)
console.log(responseData,'responseData')
// 處理上傳成功后的邏輯
if(responseData.code==200){
this.contractImage1 = responseData.data
uni.setStorageSync('faceUrl',this.contractImage1)
}else{
uni.$u.toast(responseData.msg);
}
} else {
console.error('上傳失敗', res.statusCode);
uni.showToast({
title: res.msg, // 自定義錯(cuò)誤信息
icon: 'none'
});
}
},
fail: (err) => {
console.error('上傳失敗:', err);
uni.showToast({
title: '上傳失敗,請(qǐng)重試',
icon: 'none'
});
}
});
},
即能兼容h5也能兼容微信小程序和各個(gè)app
微信小程序圖片壓縮再次用二分查找壓縮質(zhì)量文章來源:http://www.zghlxwxcb.cn/news/detail-854619.html
// 壓縮圖片
export function compressImage(filePath, quality, successCallback, errorCallback) {
uni.compressImage({
src: filePath,
quality: quality,
success: (res) => {
successCallback(res.tempFilePath);
},
fail: (err) => {
errorCallback(err);
}
});
}
// 二分查找壓縮質(zhì)量
export function binarySearchCompress(filePath, targetSize, low, high, successCallback, errorCallback) {
if (low > high) {
errorCallback("無法達(dá)到目標(biāo)大小");
return;
}
const mid = Math.floor((low + high) / 2);
compressImage(filePath, mid, (tempFilePath) => {
uni.getFileInfo({
filePath: tempFilePath,
success: (res) => {
const currentSize = res.size;
if (currentSize <= targetSize) {
successCallback(tempFilePath);
} else {
// 遞歸調(diào)整壓縮質(zhì)量
binarySearchCompress(filePath, targetSize, low, mid - 1, successCallback, errorCallback);
}
},
fail: (err) => {
errorCallback(err);
}
});
}, (err) => {
errorCallback(err);
});
}
vue文件引用文章來源地址http://www.zghlxwxcb.cn/news/detail-854619.html
//#ifdef APP-PLUS || MP-WEIXIN
// 如果超過200KB,進(jìn)行壓縮
const tempFilePath = chooseImageRes.tempFilePaths[0];
const targetSizeKB = 200;
// 將目標(biāo)大小轉(zhuǎn)換為字節(jié)數(shù)
const targetSize = targetSizeKB * 1024;
// 初始?jí)嚎s質(zhì)量范圍
const lowQuality = 1;
const highQuality = 100;
binarySearchCompress(tempFilePath, targetSize, lowQuality, highQuality, (compressedFilePath) => {
console.log("壓縮成功,壓縮后圖片路徑:", compressedFilePath);
this.uploadCompressedImage(compressedFilePath);
}, (err) => {
console.error("壓縮失?。?, err);
})
//#endif
到了這里,關(guān)于uniapp 上傳壓縮圖片 兼容h5和小程序的方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!