项目近期有一个需求,是在小程序上传图片或者选择多张图片时,页面缩略图和上传服务器的图片都是带水印的,水印文案是当前的时间和当前所处的地点。

<!-- 添加水印 -->
<view hidden = "{{ !watermark }}"><mp-uploader bindfail="uploadError" bindsuccess="uploadSuccess" binddelete="delete" select="{{selectFile}}" files="{{files}}" upload="{{uplaodFile2}}" max-count="{{maxCount}}" title="{{title}}" tips="{{tip}}"></mp-uploader><view style='width:0px;height:0px;overflow:hidden;position:fixed;left:90000000px;z-index:-999;'><canvas wx:for="{{canvasArray}}" wx:key="key" canvas-id="canvasId{{index}}" style="width: {{item.width}}px;height: {{item.height}}px;"></canvas></view>
</view><!-- 不添加水印 -->
<view hidden = "{{ watermark }}"><mp-uploader bindfail="uploadError" bindsuccess="uploadSuccess" binddelete="delete" select="{{selectFile}}" files="{{files}}" upload="{{uplaodFile}}" max-count="{{maxCount}}" title="{{title}}" tips="{{tip}}"></mp-uploader>
</view>

const app = getApp()
const http = require('../../utils/http')
// 引入SDK核心类
var QQMapWX = require('../../utils/qqmap-wx-jssdk')//申请密钥地址
var qqmapsdk = new QQMapWX({ key: 'PBPBZ-HHOW3-4H63F-YZDHC-HAJP3-VJBSK' })Component({options: {styleIsolation: 'shared'},/*** 组件的属性列表*/properties: {files: {type: Array,value: []},title: {type: String,value: '图片上传'},tip: {type: String,value: ''},maxCount: { // 最多上传张数type: Number,value: 7},watermark: {type: Boolean,value: false}},/*** 页面的初始数据*/data: {canvasArray: [], // DOM创建canvas的数组pics: [], // 上传到服务器的图片promisePics: [], // 上传图片队列address: ''},ready: function () {this.setData({selectFile: this.selectFile.bind(this),uplaodFile: this.uplaodFile.bind(this),uplaodFile2: this.uplaodFile2.bind(this)})http.get('huawei/obs').then(res => {this.setData({ huawei: res })})const that = thiswx.getLocation({isHighAccuracy: true, // 开启地图精准定位type: 'gcj02', // 地图类型写这个// type: 'wgs84',success: function(res) {//用腾讯地图的api,根据经纬度定位当前位置信息qqmapsdk.reverseGeocoder({location: {latitude: res.latitude,  // 回调的纬度longitude: res.longitude // 回调的经度},//回调成功显示位置的详细数据success:(res)=> {that.setData({ address: res.result.address })},//回调失败  (调用成功之后这个可以不需要 ,回调失败会有报错信息方便调试)fail: function (res) {console.log(res)},//成功失败都会执行complete: function (res) {console.log(res)}})},})},/*** 组件的方法列表*/methods: {selectFile (files) {// 返回false可以阻止某次文件上传},uplaodFile (files) {files.tempFilePaths.map(file => {const key = 'miniprogram/' + Math.random().toString(36).substr(2) + '.jpg';const formData = {};if (this.data.huawei) {formData.policy = this.data.huawei.policy;formData.signature = this.data.huawei.signature;formData.AWSAccessKeyId = this.data.huawei.AccessKeyId;formData['Content-Type'] = 'image/jpeg';}formData.key = key;wx.uploadFile({url: app.globalData.imgHost,header: {},filePath: file,name: 'file',formData: formData,success: (res) => {// console.log('success', res);if (res.errMsg == 'uploadFile:ok') {if ( typeof (res.header.Location) == 'string' ) {this.setData({ files: [...this.data.files, { url: app.globalData.imgHost + (res.header.Location).substring(res.header.Location.indexOf('/miniprogram')) }]})} else {let location = (res.header.Location)[0]this.setData({ files: [...this.data.files, { url: app.globalData.imgHost + location.substring(location.indexOf('/miniprogram')) }]})}this.triggerEvent('change', this.data.files.map(file => file.url))}},complete: (res) => {console.log('complete', res);}})})// 文件上传的函数,返回一个promisereturn new Promise((resolve, reject) => {resolve(this.data.files)})},// 上传图片 // 参数: filesuplaodFile2 (files) {wx.showLoading({ title: "正在加载图片", mask: true })const { tempFilePaths } = files// 获取动态生成canvas的数组let canvasArr = tempFilePaths.map( item => {if (typeof item == 'string') { return {'url': item} } else { return item }})this.setData({ canvasArray: canvasArr })this.uploadFileAll(tempFilePaths).then(res => {console.log("所有接口都请求完了", res)})// 图片上传的函数,返回Promise,Promise的callback里面必须resolve({urls})表示成功,否则表示失败return new Promise((resolve, reject) => {resolve({ urls: this.data.promisePics })// 清空上传图片队列this.setData({ promisePics: [] })})},uploadFileAll (tempFilePaths) {return new Promise( (resolve, reject) => {let arr2 = []tempFilePaths.map( (item, index) => {const promise = new Promise( (res, rej) => {this.imgPromise(item, index)res()})arr2.push(promise)})Promise.all(arr2).then((result) => {resolve()  // 所有接口都执行完毕})} )},// 返回图片上传promiseimgPromise (item, index) {return new Promise( (resolve, reject) => {const that = thiswx.getImageInfo({src: item,success(res) {// 设置对应的canvas的宽高let canvasArray = that.data.canvasArraycanvasArray[index].width = res.widthcanvasArray[index].height = res.heightthat.setData({ canvasArray: canvasArray })// canvas添加水印that.getCanvasImg(res, index).then(pImg => {resolve(pImg)}).catch(err => {reject(err)})}})})},// canvas添加水印getCanvasImg(imgInfo, index) {return new Promise( (resolve, reject) => {const that = thislet { path, width, height } = imgInfo// 图片添加水印// 获取当前时间let newDate = new Date()let year = newDate.getFullYear() //年let month = newDate.getMonth() + 1 //月let day = newDate.getDate() //日var hour = newDate.getHours()var minute = newDate.getMinutes()var second = newDate.getSeconds()let roleNameInfo = '拍摄时间:' + year + '年' + month + '月' + day + '日 '+ hour+':'+minute +':' + secondlet address = '上海市'// 创建canvasconst ctx = wx.createCanvasContext('canvasId'+index, that)ctx.drawImage(path, 0, 0, width, height) // 先画出图片// 将声明的时间放入canvaslet fontSize = 30if (width >= 1500) { fontSize = 80 } else if (width >= 1000) { fontSize = 60 }ctx.setFontSize(fontSize) //注意:设置文字大小必须放在填充文字之前,否则不生效ctx.setFillStyle('rgba(255, 255, 255, 0.5)')ctx.shadowOffsetX = -6 //用来设定阴影在 X轴的延伸距ctx.shadowOffsetX = -6 //用来设定阴影在 Y轴的延伸距ctx.shadowBlur = 3 //设定阴影的模糊程度 默认0ctx.shadowColor = "rgba(0, 0, 0, 0.3)" //设定阴影颜色效果ctx.fillText(roleNameInfo, 20, height/8)ctx.fillText(that.data.address, 20, height/8+fontSize+10)ctx.draw(false, function () {// 绘画完成回调// 生成图片 把当前画布指定区域的内容导出生成指定大小的图片。在 draw() 回调里调用该方法才能保证图片导出成功wx.canvasToTempFilePath({quality: 1,fileType: 'jpg',canvasId: 'canvasId'+index,// destWidth: width, // 输出的图片的宽度// destHeight: height, // 输出的图片的高度// width: width,// height: height,success: function (res) {that.handleUpload(res.tempFilePath).then( _=> { // res.tempFilePath 最终图片路径resolve()})},fail: function(res) {reject(res)}}, that)})})},// 上传图片方法handleUpload (img) {return new Promise( (resolve, reject) => {const that = thisconst key = 'miniprogram/' + Math.random().toString(36).substr(2) + '.jpg'const formData = {};if (that.data.huawei) {formData.policy = that.data.huawei.policyformData.signature = that.data.huawei.signatureformData.AWSAccessKeyId = that.data.huawei.AccessKeyIdformData['Content-Type'] = 'image/jpeg'}formData.key = keywx.uploadFile({url: app.globalData.imgHost,filePath: img,name: 'file',formData: formData,success: (res) => {wx.hideLoading()if(res.errMsg == 'uploadFile:ok') { // 上传成功let url = ''let { pics, promisePics } = that.datapromisePics.push( img )if ( typeof (res.header.Location) == 'string' ) {url = app.globalData.imgHost + res.header.Location.substring(res.header.Location.indexOf('/miniprogram'))} else {let location = (res.header.Location)[0]url = app.globalData.imgHost + location.substring(location.indexOf('/miniprogram'))}pics.push(url)that.setData({ pics, promisePics, files: [...this.data.files, { url: url } ] })that.triggerEvent('change', this.data.files.map(file => file.url))}},fail: (error) => {wx.hideLoading()console.log('error', error)}})})},delete (e) {this.data.files.splice(e.detail.index, 1)this.setData({ files: this.data.files })this.triggerEvent('change', this.data.files.map(file => file.url))},change: function () {this.triggerEvent('change', this.data)},uploadError(e) {console.log('upload error', e.detail)},uploadSuccess(e) {console.log('upload success', e.detail)}},export () {return this.data}
})

微信小程序上传图片使用canvas添加水印相关推荐

  1. 微信小程序--上传图片加水印

    微信小程序–上传图片加水印 wxml <canvas class='canvas' canvas-id="firstCanvas"></canvas> cs ...

  2. 微信小程序上传图片到服务器总是失败_微信小程序上传图片过大导致请求失败的解决方法...

    很多时候我们都会碰到小程序上传图片时因为图片过大而导致请求失败,同时出现各种各样的问题,那么今天来给大家写一个微信小程序上传图片过大导致请求失败的完美解决办法. 以云开发小程序图片检测为例,如果图片过 ...

  3. 微信小程序上传图片 预览 删除

    微信小程序上传图片 预览 删除 ①.wxml<view class='footerEditOne'><view wx:for="{{src}}" wx:key=' ...

  4. 微信小程序上传图片至服务器Springboot接收格式的问题

    微信小程序上传图片至服务器Springboot 需求:通过微信小程序上传图片到服务器,保存至服务器. 实现 Wxml <button bindtap="choose"> ...

  5. 微信小程序上传图片写法

    微信小程序上传图片 小程序上传图片需要用到小程序API中的wx.uploadFile()方法.以下是一个基本的示例代码: wx.chooseImage({count: 1,sizeType: ['or ...

  6. 微信小程序之用canvas给微信头像加小红旗(canvas无法使用网络资源绘画)

    微信小程序之使用canvas给微信头像加小红旗 情境:新中国成立70周年,普天同庆.昨天看到朋友圈中被刷屏的@官方微信 给自己的头像加小红旗.服务器被卡爆,很多朋友说换头像不成功. 任务:打算自己写一 ...

  7. 微信小程序上传图片到服务器总是失败_微信小程序怎么上传图片到服务器?

    微信小程序怎么上传图片到服务器?相信很多人都会把小程序图片保存到本地吧,但是把图片上传到服务器就不一定了,下面一起随小编看看微信小程序怎么上传图片到服务器吧. 微信小程序怎么上传图片到服务器? 首先, ...

  8. 微信小程序上传图片组件,多选+单选+预览+删除

    微信小程序上传图片+预览+删除 组件代码 HTML <view class="uploadImg-wrap"><view class="upload-f ...

  9. 在H5、微信小程序中使用canvas绘制二维码、分享海报

    在H5.微信小程序中使用canvas绘制二维码.分享海报 文章目录 在H5.微信小程序中使用canvas绘制二维码.分享海报 前言 一.canvas绘制二维码 1.H5中使用canvas 2.微信小程 ...

  10. 微信小程序上传图片到七牛云

    七牛云上传图片 第一次用七牛云,目的是存储一些图片 1.首先是七牛云的注册,很简单. 2.注册完创建新的空间 3.这时候会自动分配给你一个域名,但是有效期是30天. 4.若要长久使用,最好用自己的域名 ...

最新文章

  1. Spring Boot 获取 Bean 的 3 种方式!还有谁不会?
  2. 12. Leetcode 350. 两个数组的交集 II (数组-分离双指针)
  3. HarmonyOS应用开发——使用HUAWEI DevEco Studio创建第一个程序 HELLO WORLD!
  4. [转载]Oracle ltrim() 函数用法
  5. linux mysql导出乱码问题_[MYSQL]将数据从5.0版本导入到4.1.7版本中出现乱码问题解决方案...
  6. [导入]需要关注的十大安全技巧之:免受垃圾邮件侵扰
  7. GICv3驱动初始化
  8. Gateway网关系列(二):SpringCloud Gateway入门实战,路由规则
  9. php格式转换rar,如何在PHP中创建压缩的RAR文件?
  10. html不用ajax怎么提交,停止HTML中JS AJAX功能提交按钮
  11. 中国数字音乐——版权问题之公司分析
  12. Rider编译UE5项目RD报错
  13. java 调用科大讯飞 实现会议录音,语音转写会议既要功能
  14. 人,总要敢于直面自己的惨淡,才能挺直腰杆
  15. 解决state_enabled=false 不起作用的
  16. Unbuntu ./btest : cannot execute binary file: Exec format error解决方案(CSAPP)
  17. 字体图标转png透明图标——小程序开发用
  18. python在电脑上怎样下载_怎样在电脑上下载哔哩哔哩的视频?
  19. APP开发商城时,常说三级分销,你知道什么是分销机制吗?
  20. 成功安装fbprophet(没有坑也没有眼泪,世上最详细步骤)

热门文章

  1. Hive教程(03)- Hive数据模型
  2. 开心盒子助手3.0版|开心盒子助手工具3.0电脑版
  3. win11字体模糊不清怎么办 windows1字体模糊不清的解决方法
  4. android运行win7系统,安卓手机安装运行Win7系统教程(图文)
  5. 如何压缩图片大小?这几种图片压缩方法总有一款适合你
  6. 2018-10-8-如何安装-btsync
  7. MySQL数据库高级应用(北理珠实验答案)
  8. web前端面试题(必背面试题)
  9. 2017年全国数学建模国赛B题题目、解题思路、matlab代码(三)
  10. 1.4 px30驱动移植-网卡驱动找不到网卡解决