小程序上传图片添加水印传

我的需求是:手机拍照成功后,获取当前时间和地点印在照片上传给后台。 如果是自定义文字的话那就不要位置授权了
//微信wxml--------------------------------------------------------------
<!-- 图片上传 -->
  <view class='up-pic' style="padding-bottom:100rpx;">
    <view class='row pic-box'>
    <text class="file_title">图片上传:</text>
      <block wx:key="imgbox" wx:for="{
   
   {picArr}}">
        <view class='add-pic'>
          <image class='add-pic' src="{
   
   {item}}" data-index="{
   
   {index}}" bindtap="picPreview"></image>
          <view class='img-de'  bindtap="deleteImg" data-index="{
   
   {index}}">
            x
          </view>
        </view>
      </block>
      <view class='add-pic'>
        <view class='btn' bindtap='chooseImage'>+</view>
      </view>
    </view>
  </view>
  <canvas class='left-hidden' style="width: 100%; height: {
   
   {setHeight}}px;" canvas-id="myCanvas"></canvas>
  wxss部分---------------------------------------------------------------------
  .up-pic{  
  width: 100%;  
  padding-bottom: 200rpx;
  justify-content: center;
  background: #fff;
}  
.pic-box{  
  flex-flow:wrap;  
   width:95%;
   margin-bottom: 30rpx;
}  
.ap-box{  
   position: relative;  
}  
.add-pic{  
  width: 108rpx;  
  height: 108rpx;  
  margin-right: 20rpx;  
  position: relative;  
  margin: 20rpx 30rpx 20rpx 30rpx;  
}  
/* 删除图片 */  
.img-de{  

  position:absolute;
  width:18px;
  height:18px;
  border-radius:50%;
  background:#ff5100;
  border:1px solid white;
  top:-3px;
  text-align:center;
  color:white;
  cursor:pointer;
  right:-20px;
  line-height:15px;
  font-size:14px;
}
.w100{
  width: 750px;
  text-align: center;
}
//JS部分-------------------------------------------------------------------------------------
//这是腾讯位置授权
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js');  
var qqmapsdk;
//上传图片 接口
var uploadFileMoney = function (params, that) {
  wx.showLoading({
    title: '正在上传',
  })
  serverInterface2.payUpfile({
    data: params,
    success: function (res) {
      const { attachment, status, statusText } = JSON.parse(res.data)
      if (status === 200) {
        wx.hideLoading();
        that.setData({
          saveIdPic: that.data.saveIdPic.concat(attachment)
        })
      } else {
        wx.showToast({
          title: '上传失败',
          image: '../../../images/iconalert.png'
        })
      }
    }
  })
}
Page({
data{
 picArr: [],
    attachmentId: "",
    saveIdPic: [],
    ctx: '',
    setWidth: '',
    setHeight: '500',
    setheught: '',
    // 文件上传
    saveIdFile:[],
    // 位置
    addRess: '',
},
  /**
 * 生命周期函数--监听页面加载
 */
  onLoad: function (options) {
    // 上传获取位置 S
    var ctx = wx.createCanvasContext('myCanvas', this)
    this.setData({
      ctx: ctx
    })
    // 位置:
    qqmapsdk = new QQMapWX({
      key: 'asdad212312aSasAS' //这里自己的key秘钥进行填充,开通位置后可查看
    });
    // 上传获取位置 E
  },
    // 上传图片先授权位置
  chooseImage: function (e) {
    let that = this
    let obj = { latitude: '', longitude: '' }
    // 调取经纬度
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        console.log("同意")
        obj.latitude = res.latitude
        obj.longitude = res.longitude
        that.upFilePic(obj)
      } , fail: (e) => {
        console.log("不同意")
        obj.latitude = ''
        obj.longitude = ''
        that.upFilePic(obj)
      }
    })
  },
    // 上传图片
  upFilePic: function (obj) {
    let ctx = this.data.ctx
    let that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        var tempFilePaths = res.tempFilePaths
        console.log(res)
        //  是否获取地址 tempFilePaths为照片url
        that.getLocal(obj.latitude, obj.longitude, tempFilePaths)
      }
    })
  },
   // 显示位置并添加水印
  getLocal: function (latitude, longitude, tempFilePaths) {
    let that = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        let address = res.result.address   //地址
        that.setData({
          addRess: address
        })
        // 新增图片添加水印后再上传至后台
        let createTime = util.getTimeNow() //当前时间,我这里封装了公共方法,你可以自己写
        //获取图片基本信息
        let ctx = that.data.ctx
        wx.getImageInfo({
          src: tempFilePaths[0],
          success: function (res) {
            var width = res.width
            var height = res.height
            var realRatio = width / height
            //获取屏幕宽度
            let screenWidth = wx.getSystemInfoSync().windowWidth
            //处理一下图片的宽高的比例
            width = screenWidth
            height = screenWidth / realRatio
            if (height > 350) {
              that.setData({
                setWidth: width,
                setHeight: 500
              })
            } else if (height <= 200) {
              that.setData({
                setWidth: width,
                setHeight: 200,
              })
            }
            else if (200 < height <= 300) {
              that.setData({
                setWidth: width,
                setHeight: 250,
              })
            }
            else if (300 < height <= 350) {
              that.setData({
                setWidth: width,
                setHeight: 320,
              })
            }
            ctx.drawImage(res.path, 0, 0, width, that.data.setHeight)
            // ctx.rotate(Math.PI / 180);  //旋转
            for (let j = 1; j < 2; j++) {
              ctx.beginPath()
              ctx.setFontSize(9)
              ctx.setFillStyle('red')
              ctx.translate(10, 40);
              ctx.fillText(that.data.addRess, 0, that.data.setHeight - 50)
            }
            for (let j = 0; j < 1; j++) {
              ctx.beginPath()
              ctx.setFontSize(9)
              ctx.setFillStyle('red')
              ctx.fillText(createTime, 0, that.data.setHeight - 70)
            }
            ctx.draw(false, function () {
              wx.canvasToTempFilePath({
                canvasId: 'myCanvas',
                success: (res) => {
                  let imgeList = that.data.picArr.concat(res.tempFilePath);  //图片显示的url,
                  that.setData({
                    picArr: imgeList,
                    setWidth: width,
                    setHeight: '500'
                  });
                  // 画好照片后传给后台
                  console.log(res.tempFilePath)
                  let params = {
                    fileUrl: res.tempFilePath,   //画好后的图片,一张一张的上传
                    latitude: latitude,
                    longitude: longitude,
                    address: that.data.addRess
                  }
                  uploadFileMoney(params, that)     //传给后台,这是后台接口
                },
                fail: (e) => {
                }
              }, that)
            })
          }
        })
        // 新增图片添加水印后再上传至后台结束
   
      },
      fail: function (res) {
        let params = {
          fileUrl: tempFilePaths[0],
          latitude: latitude,
          longitude: longitude,
          address: that.data.addRess
        }
        uploadFileMoney(params, that)
      },
      complete: function (res) {
      }
    });
  },
  // 图片预览
  picPreview(e) {
    let imgUrl = this.data.picArr[e.currentTarget.dataset.index]
    wx.previewImage({
      current: imgUrl,
      urls: this.data.picArr
    })
  },
  // 删除图片
  deleteImg: function (e) {
    let that = this
    let index = e.currentTarget.dataset.index;
    let images = that.data.picArr;
    let saveIdPic = that.data.saveIdPic;
    images.splice(index, 1);
    saveIdPic.splice(index, 1);
    that.setData({
      picArr: images,
      saveIdPic: saveIdPic
    });
  },
 })

猜你喜欢

转载自blog.csdn.net/weixin_41760500/article/details/104694577