uniapp 加图片水印示例

1.需要先在view中增加一个canvas

        
        

2.这里的两个参数只需要关注第一个path就行了,为相册选择的图片地址或者拍照得到的图片地址

// 增加水印并保存到相册
            watermark(path, name) {
                // 获取图片信息
                uni.getImageInfo({
                    src: path,
                    success: function(image) {
                        _this.canvasSiz.width = image.width;
                        _this.canvasSiz.height = image.height;

                        //担心尺寸重置后还没生效,故做延迟
                        setTimeout(() => {
                            let ctx = uni.createCanvasContext('canvas-clipper', _this);
                            ctx.drawImage(
                                path,
                                0,
                                0,
                                image.width,
                                image.height
                            );
                            // 设置文字水印
                            ctx.setFillStyle('white');
                            ctx.setFontSize(30);
                            ctx.fillText('抄表日期:', 20, 100);


                            //再来加个时间水印
                            var date = new Date();
                                                        //这里用了uview的js如果不适配需要自行修改
                            var time = _this.$u.timeFormat(date, 'yyyy年mm月dd日 hh时MM分ss秒')
                            ctx.setFontSize(30);
                            ctx.fillText(time, 20, 140);

                            ctx.draw(false, () => {
                                // 导出图片
                                uni.canvasToTempFilePath({
                                        destWidth: image.width,
                                        destHeight: image.height,
                                        canvasId: 'canvas-clipper',
                                        fileType: 'png',
                                        success: function(res) {
                                            _this.savePhoto(res.tempFilePath, name);
                                        }
                                    },
                                   //这个_this是当前页this在onload里面赋值的
                                    _this
                                );
                            });
                        }, 500)


                    }
                });
            },

            //保存图片到相册,方便核查
            savePhoto(path, name) {
                //保存到相册
                uni.saveImageToPhotosAlbum({
                    filePath: path,
                    success: () => {
                        uni.showToast({
                            title: '已保存至相册',
                            duration: 2000
                        });
                    }
                });
            },

3._this的声明


image.png
image.png

4.效果图


image.png

你可能感兴趣的:(uniapp 加图片水印示例)