主题
LimeShrink 图片压缩
- 在0.0.3版本之前基于uniapp vue3 canvas 实现的图片压缩插件
- 在0.0.4版本之后非web端使用uni.compressImage实现,web端对齐
uni.compressImage
API达到全端兼容。
安装
代码演示
在插件导出compressImage
函数,具体参数可以参考compressImage,文档。rotate
属性未实现。
js
import { compressImage, ShrinkImageOptions } from '@/uni_modules/lime-shrink';
uni.chooseImage({
success(res) {
compressImage({
// compressedWidth: 500,
// #ifndef WEB
src: res.tempFilePaths[0],
// #endif
// #ifdef WEB
// 在web端最好是传入file文件,方便知道要使用jpg还是png算法。如果传入的是路径,最好有后缀如.jpg|.png
src: res.tempFiles[0],
// #endif
success(res2) {
// #ifdef WEB
const manager = uni
// #endif
// #ifndef WEB
const manager = uni.getFileSystemManager()
// #endif
manager.getFileInfo({
filePath: res.tempFilePaths[0],
success(res){
console.log('压缩前', res.size)
}
})
manager.getFileInfo({
filePath: res2.tempFilePath,
success(res){
console.log('压缩后', res.size)
}
})
}
} as ShrinkImageOptions)
}
})
旧方法 废除
以前uniapp的组件方式还保留。但不再推荐使用。如果你之前有使用该插件,麻烦使用上面的方法实现。
html
<l-shrink ref="shrinkRef"></l-shrink>
js
const shrinkRef = ref(null)
// 支持数组
// compressImage(file|file[], options:{quality: number})
// quality: 0-100之间,默认80
const res = await shrinkRef.value.compressImage('/static/logo.png');
// 批量
const res = await shrinkRef.value.compressImage(['/static/logo.png', '/static/logo1.png'], {quality: 75});
查看示例
- 导入后直接使用这个标签查看演示效果
html
<!-- // 代码位于 uni_modules/lime-shrink/compoents/lime-shrink -->
<lime-shrink />
插件标签
- 默认 l-shrink 为 component
- 默认 lime-shrink 为 demo
关于vue2的使用方式
- 插件使用了
composition-api
, 如果你希望在vue2中使用请按官方的教程vue-composition-api配置 - 关键代码是: 在main.js中 在vue2部分加上这一段即可.
js
// main.js vue2
import Vue from 'vue'
import VueCompositionAPI from '@vue/composition-api'
Vue.use(VueCompositionAPI)
常见问题
png 无法压缩组件方式是使用canvas绘制,所以无法压缩png,0.0.4之后使用web uts api可以。
打赏
如果你觉得本插件,解决了你的问题,赠人玫瑰,手留余香。