uniapp 编辑图片
图片裁剪与压缩
使用 uni.chooseImage 选择图片后,可通过 uni.compressImage 压缩图片。示例代码:
uni.chooseImage({
count: 1,
success: (res) => {
uni.compressImage({
src: res.tempFilePaths[0],
quality: 80, // 压缩质量
success: (compressedRes) => {
console.log(compressedRes.tempFilePath);
}
});
}
});
图片滤镜与特效
借助第三方插件如 uView UI 或手动实现滤镜效果。通过 Canvas 或 CSS 滤镜属性调整图片样式:

// Canvas 实现灰度滤镜
const ctx = uni.createCanvasContext('myCanvas');
ctx.drawImage(tempFilePath, 0, 0, 200, 200);
ctx.setFillStyle('rgba(0, 0, 0, 0.5)');
ctx.fillRect(0, 0, 200, 200);
ctx.draw();
图片旋转与缩放
通过 uni.getImageInfo 获取图片信息后,使用 CSS 或 Canvas 调整:

uni.getImageInfo({
src: tempFilePath,
success: (info) => {
const { width, height } = info;
// 缩放逻辑
const scaleRatio = Math.min(200 / width, 200 / height);
this.setData({ imgStyle: `transform: scale(${scaleRatio})` });
}
});
图片标注与涂鸦
利用 Canvas 实现涂鸦功能,监听触摸事件绘制路径:
let points = [];
Page({
touchStart(e) {
points.push({ x: e.touches[0].x, y: e.touches[0].y });
},
touchMove(e) {
const ctx = uni.createCanvasContext('canvas');
ctx.setStrokeStyle('red');
ctx.setLineWidth(2);
ctx.moveTo(points[points.length - 1].x, points[points.length - 1].y);
ctx.lineTo(e.touches[0].x, e.touches[0].y);
ctx.stroke();
ctx.draw(true);
points.push({ x: e.touches[0].x, y: e.touches[0].y });
}
});
图片保存与分享
编辑完成后,调用 uni.saveImageToPhotosAlbum 保存至相册,或 uni.share 分享:
uni.saveImageToPhotosAlbum({
filePath: tempFilePath,
success: () => {
uni.showToast({ title: '保存成功' });
}
});
注意事项
- 图片处理涉及权限时,需在
manifest.json中配置requiredPrivateInfos(如 iOS 的相册权限)。 - 大图处理建议分片操作,避免内存溢出。
- 跨平台差异需测试,如 Canvas 在 H5 和小程序中的 API 差异。






