uniapp图片的编辑
图片压缩
使用uni.compressImageAPI对图片进行压缩处理。该API可指定压缩质量,适合上传前减小文件体积。示例代码:
uni.compressImage({
src: '/static/test.jpg',
quality: 80,
success: res => {
console.log(res.tempFilePath)
}
})
图片裁剪
通过uni.chooseImage选择图片后,配合canvas实现裁剪功能。需要创建隐藏的canvas元素进行绘制:
const ctx = uni.createCanvasContext('myCanvas')
ctx.drawImage(tempFilePaths[0], 0, 0, width, height)
ctx.draw()
图片滤镜
使用CSS滤镜或WebGL实现特效。基础CSS滤镜示例:
.filter-image {
filter: brightness(1.2) contrast(0.8) sepia(0.3);
}
图片水印
通过canvas叠加文字或logo实现水印。核心绘制逻辑:
ctx.fillText('Watermark', x, y)
ctx.drawImage(watermarkImg, x, y, width, height)
图片上传
采用uni.uploadFile接口上传处理后的图片。需注意格式转换:
uni.uploadFile({
url: 'https://example.com/upload',
filePath: tempFilePath,
name: 'file',
formData: {user: 'test'}
})
性能优化
大图处理建议使用Worker线程。通过uni.createWorker创建后台任务:
const worker = uni.createWorker('workers/image.js')
worker.postMessage({ cmd: 'compress', data: imageData })
跨平台兼容
针对不同平台特性进行条件编译:
// #ifdef H5
// 浏览器特有API
// #endif
// #ifdef APP-PLUS
// 原生扩展API
// #endif






