uniapp 图像处理
图像压缩与裁剪
在UniApp中处理图像压缩和裁剪,可以使用uni.chooseImage API选择图片后,通过uni.compressImage进行压缩。设置quality参数调整压缩质量(范围1-100),width和height可指定输出尺寸。
uni.chooseImage({
success: (res) => {
uni.compressImage({
src: res.tempFilePaths[0],
quality: 80,
width: '800px',
height: '600px',
success: (compressedRes) => {
console.log(compressedRes.tempFilePath);
}
});
}
});
图片滤镜与特效
通过Canvas实现滤镜效果。创建Canvas上下文后,使用drawImage加载图片,通过getImageData和putImageData修改像素数据。例如实现灰度滤镜:

const ctx = uni.createCanvasContext('myCanvas');
ctx.drawImage('imagePath', 0, 0, 300, 200);
ctx.getImageData({
x: 0,
y: 0,
width: 300,
height: 200,
success: (res) => {
const pixels = res.data;
for (let i = 0; i < pixels.length; i += 4) {
const avg = (pixels[i] + pixels[i+1] + pixels[i+2]) / 3;
pixels[i] = pixels[i+1] = pixels[i+2] = avg;
}
ctx.putImageData({
data: pixels,
x: 0,
y: 0,
width: 300
});
ctx.draw();
}
});
图片上传与云存储
结合uniCloud实现图片上传。使用uni.uploadFile将处理后的图片上传至云存储,需注意临时文件路径的有效期:
uni.uploadFile({
url: 'https://your-cloud-service.com/upload',
filePath: compressedImagePath,
name: 'file',
formData: { 'userId': '123' },
success: (uploadRes) => {
console.log(uploadRes.data);
}
});
性能优化建议
处理大图时推荐使用Worker线程避免主线程阻塞。通过uni.createWorker创建Worker,将计算密集型任务(如像素处理)移至后台:

const worker = uni.createWorker('workers/image.js');
worker.postMessage({
imageData: base64Data,
operation: 'grayscale'
});
worker.onMessage((res) => {
console.log('处理完成', res.data);
});
跨平台兼容方案
针对不同平台(H5/小程序/App)的差异处理:
- 小程序端需注意
canvas标签的层级限制 - App端可使用原生插件如
imageTools提升性能 - H5端可通过
documentAPI直接操作DOM元素
// 条件编译示例
// #ifdef MP-WEIXIN
wx.createSelectorQuery().select('#canvas').fields({node:true}).exec((res) => {
const canvas = res[0].node;
});
// #endif
第三方库集成
推荐使用luch-request处理网络请求,或we-cropper实现高级裁剪功能。通过npm安装后需在manifest.json中配置:
"h5": {
"template": "public/index.html",
"devServer": {
"proxy": {
"/api": {
"target": "https://your-cdn.com"
}
}
}
}






