uniapp拍照加水印
实现拍照加水印功能的方法
在uniapp中实现拍照并添加水印的功能,可以通过以下步骤完成:
1. 调用相机或相册选择图片
使用uniapp的uni.chooseImageAPI选择或拍摄照片:
uni.chooseImage({
count: 1,
sourceType: ['camera', 'album'],
success: function(res) {
const tempFilePath = res.tempFilePaths[0];
addWatermark(tempFilePath); // 调用水印添加函数
}
});
2. 创建Canvas绘制水印
通过Canvas在图片上绘制文字或图片水印:
function addWatermark(imagePath) {
const ctx = uni.createCanvasContext('watermarkCanvas');
ctx.drawImage(imagePath, 0, 0, 300, 200); // 绘制原图
ctx.setFontSize(16);
ctx.setFillStyle('rgba(255, 255, 255, 0.5)');
ctx.fillText('水印文字', 20, 30); // 添加文字水印
ctx.draw();
}
3. 保存处理后的图片
使用canvasToTempFilePath将Canvas转换为图片并保存:
ctx.draw(false, function() {
uni.canvasToTempFilePath({
canvasId: 'watermarkCanvas',
success: function(res) {
const watermarkedPath = res.tempFilePath;
uni.saveImageToPhotosAlbum({
filePath: watermarkedPath,
success: function() {
uni.showToast({ title: '保存成功' });
}
});
}
});
});
注意事项
- Canvas尺寸适配:需根据设备屏幕调整Canvas宽高,避免图片变形。
- 水印样式:可通过
setFillStyle调整水印颜色和透明度,或使用rotate旋转角度。 - 权限处理:在Android上需动态申请相册和相机权限,在manifest.json中配置。
扩展功能(图片水印)
若需添加图片水印,可在Canvas中叠加绘制:
ctx.drawImage('static/logo.png', 10, 10, 50, 50); // 绘制图片水印
示例模板代码
<template>
<view>
<button @click="chooseImage">拍照加水印</button>
<canvas canvas-id="watermarkCanvas" style="width:300px;height:200px"/>
</view>
</template>






