uni-app小程序項(xiàng)目中實(shí)現(xiàn)前端圖片壓縮實(shí)現(xiàn)方式(附詳細(xì)代碼)
方式一:使用<canvas>實(shí)現(xiàn)圖片壓縮(推薦,兼容性好)
這是最常見的一種方式,通過將圖片繪制到 <canvas> 上,然后用 canvas.toTempFilePath 或 canvas.toDataURL 得到壓縮后的圖片。
示例代碼(小程序平臺(tái)):
<template>
<view>
<button @click="chooseImage">選擇圖片并壓縮</button>
</view>
</template>
<script>
export default {
methods: {
chooseImage() {
uni.chooseImage({
count: 1,
success: (res) => {
const tempFilePath = res.tempFilePaths[0];
this.compressImage(tempFilePath);
}
});
},
compressImage(path) {
// 創(chuàng)建 canvas 實(shí)例
const ctx = uni.createCanvasContext('myCanvas', this);
uni.getImageInfo({
src: path,
success: (img) => {
const maxW = 800; // 最大寬度
const scale = maxW / img.width;
const w = maxW;
const h = img.height * scale;
// 畫圖
ctx.drawImage(path, 0, 0, w, h);
ctx.draw(false, () => {
// 延遲一點(diǎn),確保畫完
setTimeout(() => {
uni.canvasToTempFilePath({
canvasId: 'myCanvas',
destWidth: w,
destHeight: h,
success: (res) => {
console.log('壓縮后圖片路徑:', res.tempFilePath);
// 可以用 res.tempFilePath 上傳或預(yù)覽
},
fail: (err) => {
console.error('canvas 轉(zhuǎn)圖片失敗', err);
}
}, this);
}, 200);
});
}
});
}
}
};
</script>
<canvas canvas-id="myCanvas" style="width: 800px; height: 600px;" />
方式二:使用uni.compressImageAPI(簡(jiǎn)單但壓縮能力有限)
這是 uni-app 封裝的一個(gè)簡(jiǎn)單壓縮接口,用于壓縮臨時(shí)文件路徑圖片
uni.chooseImage({
count: 1,
success: (res) => {
const filePath = res.tempFilePaths[0];
uni.compressImage({
src: filePath,
quality: 80, // 取值 0 - 100,越小壓縮率越高
success: (res) => {
console.log('壓縮成功:', res.tempFilePath);
},
fail: (err) => {
console.error('壓縮失?。?, err);
}
});
}
});
注意:
uni.compressImage目前只支持 App 和微信小程序平臺(tái),在 H5 和其他平臺(tái)會(huì)失效或無(wú)效果。圖片質(zhì)量壓縮效果受限,不能調(diào)整尺寸。
方式三:使用三方庫(kù)(僅 H5 適用,如compressorjs)
這種方式適合在 H5 中運(yùn)行的 uni-app 項(xiàng)目,小程序端不支持 DOM。
npm install compressorjs
import Compressor from 'compressorjs';
new Compressor(file, {
quality: 0.6,
success(result) {
console.log('壓縮后的 Blob:', result);
// 你可以用 FileReader 或 FormData 處理這個(gè)文件
},
error(err) {
console.error(err.message);
},
});
| 方式 | 平臺(tái)支持 | 優(yōu)點(diǎn) | 缺點(diǎn) |
|---|---|---|---|
| Canvas 壓縮 | ? 微信小程序、App | 自由控制尺寸和質(zhì)量,通用性強(qiáng) | 需要一定代碼量 |
uni.compressImage | ? 微信小程序、App | 簡(jiǎn)單易用 | 無(wú)法控制尺寸,兼容性不夠 |
| compressorjs | ? 僅 H5 | 封裝好,效果不錯(cuò) | 不支持小程序環(huán)境 |
最后:封裝公共方法
// utils/compressImage.js
/**
* 通用圖片壓縮函數(shù)(兼容小程序/APP/H5)
* @param {String} src 原始圖片路徑
* @param {Object} options 配置項(xiàng) { quality, width, height }
* @returns {Promise<String>} 返回壓縮后圖片路徑
*/
export function compressImage(src, options = {}) {
const { quality = 0.7, width = 800, height = null } = options;
return new Promise((resolve, reject) => {
// 判斷運(yùn)行平臺(tái)
const system = uni.getSystemInfoSync().platform;
// 優(yōu)先使用 canvas 壓縮
#ifdef MP-WEIXIN || APP-PLUS
uni.getImageInfo({
src,
success(imgInfo) {
const ratio = width / imgInfo.width;
const targetWidth = width;
const targetHeight = height || imgInfo.height * ratio;
const canvasId = 'compressCanvas';
const ctx = uni.createCanvasContext(canvasId);
ctx.drawImage(src, 0, 0, targetWidth, targetHeight);
ctx.draw(false, () => {
setTimeout(() => {
uni.canvasToTempFilePath({
canvasId,
destWidth: targetWidth,
destHeight: targetHeight,
fileType: 'jpg',
quality,
success(res) {
resolve(res.tempFilePath);
},
fail(err) {
reject(err);
}
});
}, 200);
});
},
fail: reject
});
#endif
// H5 平臺(tái)(用原圖或者 compressorjs)
#ifdef H5
// 可以在此擴(kuò)展 compressorjs 邏輯
resolve(src); // 默認(rèn)返回原圖
#endif
});
}
總結(jié)
到此這篇關(guān)于uni-app小程序項(xiàng)目中實(shí)現(xiàn)前端圖片壓縮實(shí)現(xiàn)方式的文章就介紹到這了,更多相關(guān)uni-app前端圖片壓縮內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
微信小程序web-view無(wú)法打開該頁(yè)面不支持打開的解決方法
小程序現(xiàn)在日漸成熟,功能也越來越強(qiáng)大,我們今天來一起看看小程序跳轉(zhuǎn)的問題,下面這篇文章主要給大家介紹了關(guān)于微信小程序web-view無(wú)法打開該頁(yè)面不支持打開的解決方法,需要的朋友可以參考下2023-01-01
form.submit()不能提交表單的錯(cuò)誤原因及解決方法
button的id不要設(shè)置為submit,否則可能會(huì)引起混淆,導(dǎo)致表單的submit()方法不能提交表單2014-10-10
JavaScript navigator.userAgent獲取瀏覽器信息案例講解
這篇文章主要介紹了JavaScript navigator.userAgent獲取瀏覽器信息案例講解,本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08
菜鳥也能搞懂js中typeof與instanceof區(qū)別
instanceof和typeof是兩個(gè)運(yùn)算符,在程序設(shè)計(jì)中用到,常用來判斷一個(gè)變量是否為空,或者是什么類型的,本文就來介紹一下typeof與instanceof區(qū)別,感興趣的可以了解一下2021-09-09
js實(shí)現(xiàn)異步循環(huán)實(shí)現(xiàn)代碼
這篇文章主要介紹了js實(shí)現(xiàn)異步循環(huán)實(shí)現(xiàn)代碼,需要的朋友可以參考下2016-02-02
JavaScript設(shè)計(jì)模式之外觀模式介紹
這篇文章主要介紹了JavaScript設(shè)計(jì)模式之外觀模式介紹,外觀模式是用于由于子系統(tǒng)或程序組成較復(fù)雜而提供的一個(gè)高層界面接口,使用客戶端更容易訪問底層的程序或系統(tǒng)接口,需要的朋友可以參考下2014-12-12
ExtJs中g(shù)ridpanel分組后組名排序?qū)嵗a
這篇文章主要介紹了ExtJs中g(shù)ridpanel分組后組名排序?qū)嵗a,有需要的朋友可以參考一下2013-12-12
H5+C3+JS實(shí)現(xiàn)五子棋游戲(AI篇)
這篇文章主要為大家詳細(xì)介紹了H5+C3+JS實(shí)現(xiàn)五子棋游戲AI篇,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-09-09
JS apply用法總結(jié)和使用場(chǎng)景實(shí)例分析
這篇文章主要介紹了JS apply用法總結(jié)和使用場(chǎng)景,結(jié)合實(shí)例形式分析了JS apply的基本功能、原理、使用方法及操作注意事項(xiàng),需要的朋友可以參考下2020-03-03

